﻿using CRMModel;
using FRMS.BUS.ServerPlatform;
using FRMS.DAL;
using FRMS.Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Threading;
using System.Drawing;
using System.Net.Http;
using System.Net.Http.Headers;
using FRMS_N71SP.Model;
using System.Text;

namespace FRMS.BUS
{
    public class VoucherBUS
    {
        FRMSServer fxserver;
        public int m_iCardInfoRecordIndex = 0;
        public int m_lCardInfoRecordHandle = -1;
        public Int32 m_lCardInfoSearchHandle = -1;
        public int EmployeeNoCount = 0;
        private CHCNetSDK.RemoteConfigCallback g_fCardInfoRecordCallback = null;
        public LssueinfoTODev searchinf;
        public int m_iUserCount = 0;
        public int m_iSearchPosition = 0;
        public bool m_bSearchAll = true;
        public Int32 m_lUserInfoSearchHandle = -1;
        public int m_iUserInfoRecordIndex = 0;
        public Int32 m_lUserInfoRecordHandle = -1;

        public int m_iFaceDataRecordCount = 0;
        public Int32 m_lFaceDataRecordHandle = -1;
        public int m_iFaceDataRecordIndex = 0;
        public Int32 m_lFaceDataSearchHandle = -1;

        private CHCNetSDK.RemoteConfigCallback g_fFaceDataRecordCallback = null;
        public Int32 m_lGetUserCfgHandle = -1;
        public Int32 m_lSetUserCfgHandle = -1;
        public Int32 m_lDelUserCfgHandle = -1;

        String m_strFPID;

        public VoucherBUS()
        {
            fxserver = (FRMSServer)ServicesLocator.Instance.GetService(typeof(FRMSServer));
        }

        public ResponseMessage VoucherLoad(CertificateLoad certificate, string deviceid)
        {
            ResponseMessage message = new ResponseMessage();
            CertificateLoadData message1 = new CertificateLoadData();
            message1.Command = "COM_LOAD_CERTIFICATE";
            List<CertificateLoad> list = new List<CertificateLoad>();
            certificate.startTime = Convert.ToDateTime(certificate.startTime).ToString("yyyy-MM-dd HH:mm:ss");
            certificate.endTime = Convert.ToDateTime(certificate.endTime).ToString("yyyy-MM-dd HH:mm:ss");
            list.Add(certificate);
            message1.Data = list;
            string msg = fxserver.StringToHex(JsonConvert.SerializeObject(message1));
            int datanum;
            msg = ProcessSendMsg(msg, out datanum);
            byte[] buffer = HexStringToByteArray(msg);
            string result = fxserver.SendMsgToDev(buffer, deviceid);
            if (result == "success")
            {
                bool sendresult = fxserver.Replay(datanum);
                if (sendresult)
                {
                    message.errcode = 0;
                }
                else
                {
                    message.errcode = 1;
                    message.errmsg = "下发凭证失败";
                }
            }
            else
            {
                message.errcode = 1;
                message.errmsg = result;
            }

            return message;
        }

        public ResponseMessage VoucherDelete(CertificateDelete certificate, string deviceid)
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                CertificateDeleteData message1 = new CertificateDeleteData();
                message1.Command = "COM_DELETE_CERTIFICATE";
                List<CertificateDelete> list = new List<CertificateDelete>();
                list.Add(certificate);
                message1.Data = list;
                string msg = fxserver.StringToHex(JsonConvert.SerializeObject(message1));
                int datanum;
                msg = ProcessSendMsg(msg, out datanum);
                byte[] buffer = HexStringToByteArray(msg);
                string result = fxserver.SendMsgToDev(buffer, deviceid);
                if (result == "success")
                {
                    bool sendresult = fxserver.Replay(datanum);
                    if (sendresult)
                    {
                        message.errcode = 0;
                    }
                    else
                    {
                        message.errcode = 1;
                        message.errmsg = "删除凭证失败";
                    }
                }
                else
                {
                    message.errcode = 1;
                    message.errmsg = result;
                }
            }
            catch
            {
                message.errcode = 1;
                message.errmsg = "设备删除凭证失败";
            }
            return message;
        }

        public ResponseMessage VoucherClear(CertificateClear certificate, string deviceid)
        {
            ResponseMessage message = new ResponseMessage();
            CertificateClearData message1 = new CertificateClearData();
            message1.Command = "COM_DELETE_CERTIFICATE_IN_BATCH";
            List<CertificateClear> list = new List<CertificateClear>();
            list.Add(certificate);
            message1.Data = list;
            string msg = fxserver.StringToHex(JsonConvert.SerializeObject(message1));
            int datanum;
            msg = ProcessSendMsg(msg, out datanum);
            byte[] buffer = HexStringToByteArray(msg);
            string result = fxserver.SendMsgToDev(buffer, deviceid);
            if (result == "success")
            {
                bool sendresult = fxserver.Replay(datanum);
                if (sendresult)
                {
                    message.errcode = 0;
                }
                else
                {
                    message.errcode = 1;
                    message.errmsg = "清除凭证失败";
                }
            }
            else
            {
                message.errcode = 1;
                message.errmsg = result;
            }
            return message;
        }

        public ResponseMessage DeleteVoucher(VoucherInfo voucherInfo)
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                if (voucherInfo.DeviceType == 1)
                {
                    LssueVoucher lssue = new LssueVoucher();
                    lssue.m_lUserID = voucherInfo.m_lUserID;
                    lssue.DevID = voucherInfo.DeviceID;
                    lssue.UserID = voucherInfo.UUID;
                    lssue.ownerid = voucherInfo.OwnerID;
                    message = DeleteByEmployeeNo(lssue);
                }
                else
                {
                    CertificateDelete certificate = new CertificateDelete();
                    certificate.credenceNo = voucherInfo.CardNO;
                    certificate.CredenceType = 2;
                    certificate.subDeviceID = voucherInfo.DeviceNO;
                    certificate.userID = voucherInfo.UUID;
                    message = VoucherDelete(certificate, voucherInfo.DeviceNO);
                    if (message.errcode == 0)
                    {
                        DelVoucher(voucherInfo);
                    }
                }
            }
            catch
            {
                message.errcode = 1;
                message.errmsg = "凭证删除异常";
            }
            return message;
        }

        public ResponseMessage ParameterSet(ParameterSet parameter, string deviceid)
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                ParameterSetMessage message1 = new ParameterSetMessage();
                message1.Command = "COM_SETTING_PARAMETERS";
                parameter.intervalTime = "0";
                List<ParameterSet> list = new List<ParameterSet>();
                list.Add(parameter);
                message1.Data = list;
                string msg = fxserver.StringToHex(JsonConvert.SerializeObject(message1));
                int datanum;
                msg = ProcessSendMsg(msg, out datanum);
                byte[] buffer = HexStringToByteArray(msg);
                string result = fxserver.SendMsgToDev(buffer, deviceid);
                if (result == "success")
                {
                    bool sendresult = fxserver.Replay(datanum);
                    if (sendresult)
                    {
                        message.errcode = 0;
                    }
                    else
                    {
                        message.errcode = 1;
                        message.errmsg = "参数设置失败";
                    }
                }
                else
                {
                    message.errcode = 1;
                    message.errmsg = result;
                }
            }
            catch
            {
                message.errcode = 1;
                message.errmsg = "参数设置异常";
            }
            return message;
        }

        public static byte[] HexStringToByteArray(string s)
        {
            s = s.Replace(" ", "");
            byte[] buffer = new byte[s.Length / 2];
            for (int i = 0; i < s.Length; i += 2)
                buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16);
            return buffer;
        }

        public string ProcessSendMsg(string data, out int datanum)
        {
            int packnum = fxserver.GetPackNum();
            datanum = packnum;
            string datapack = IntToHex(packnum).PadLeft(8, '0');
            string datazs = datapack.Substring(0, 2) + " " + datapack.Substring(2, 2) + " " + datapack.Substring(4, 2) + " " + datapack.Substring(6, 2);
            string strCmd = data;
            int num = data.Split(' ').Length;
            string datalength = fxserver.IntToHex(num).PadLeft(8, '0').ToUpper();
            string length1 = datalength.Substring(0, 2) + " " + datalength.Substring(2, 2) + " " + datalength.Substring(4, 2) + " " + datalength.Substring(6, 2);
            string crc = fxserver.CRCCalc(strCmd);
            strCmd = "48 44 58 4D " + fxserver.StringToHex("00000000000000000000") + " " + fxserver.StringToHex("00000000000000000000") + " 00 " + datazs + " " + length1 + " 00 00 " + crc + " " + strCmd;

            return strCmd;
        }

        public string IntToHex(int num)
        {
            string result = "";
            result = Convert.ToString(num, 16).ToUpper();
            return result;
        }

        public ResponseMessage AddVoucher(VoucherInfo voucherInfo)
        {
            ModbusRtu modbus = new ModbusRtu();

            ResponseMessage message = new ResponseMessage();
            VoucherDAL da = new VoucherDAL();
            OwnerDAL ownerDAL = new OwnerDAL();
            OwnerInfo ownerInfo = ownerDAL.LoadOwnerInfo(voucherInfo.OwnerID);
            List<OwnerInfo> list = ownerDAL.QueryOwnerByPID(ownerInfo.ID);
            if (voucherInfo.OwnerType == 2)
            {
                //voucherInfo.AuthData = voucherInfo.pFloorInfo;
                if (voucherInfo.apply_type==3)
                {
                    voucherInfo.AuthData = modbus.GetCallAdminCmdByLadderID(ownerInfo.UUID,voucherInfo.LadderID);
                }
                else
                {
                    voucherInfo.AuthData = modbus.GetCallAdminCmd(ownerInfo.UUID);
                }
            }
            else
            {
                string phyfloor = SortFloor(voucherInfo.AuthorizedFloor, voucherInfo.FloorInfo, voucherInfo.pFloorInfo);
                if (voucherInfo.apply_type == 3)
                {
                    voucherInfo.AuthData = modbus.GetCallAdminCmdByLadderID(ownerInfo.UUID, voucherInfo.LadderID);
                }
                else
                {
                    voucherInfo.AuthData = modbus.GetCallCmd(phyfloor, ownerInfo.UUID);
                }
            }
            //查询该设备下，该业主主卡及副卡凭证信息
            Dictionary<int, VoucherInfo> vouvher_dic = new Dictionary<int, VoucherInfo>();
            List<VoucherInfo> vou_list = da.QueryListByDev(voucherInfo.OwnerID, voucherInfo.DeviceID, voucherInfo.projectID);
            vouvher_dic = vou_list.ToDictionary(key => key.OwnerID, value => value);
            //副卡循环更新凭证
            foreach (var item in list)
            {
                bool result = LoopVoucher(vouvher_dic, item.ID, voucherInfo);

                if (!result)
                {
                    message.errcode = 1;
                    message.errmsg = "凭证新增失败";
                    return message;
                }
            }
            //主卡更新凭证
            bool result1 = LoopVoucher(vouvher_dic, voucherInfo.OwnerID, voucherInfo);
            if (!result1)
            {
                message.errcode = 1;
                message.errmsg = "凭证新增失败";
            }

            return message;
        }

        public string SortFloor(string AuthorizedFloor, string FloorInfo, string pFloorInfo)
        {
            string floor = string.Empty;
            string[] datas = AuthorizedFloor.Split(',');
            string[] array = FloorInfo.Split(',');
            string[] pfloor_array = pFloorInfo.Split(',');
            foreach (string value in datas)
            {
                int index = array.ToList().IndexOf(value);
                if (index >= 0)
                {
                    floor += pfloor_array[index] + ",";
                }
            }
            if (!string.IsNullOrEmpty(floor))
            {
                floor = floor.TrimEnd(',');
            }
            return floor;
        }

        public bool LoopVoucher(Dictionary<int, VoucherInfo> vouvher_dic, int ownerid, VoucherInfo voucherInfo)
        {
            VoucherInfo info;
            VoucherDAL da = new VoucherDAL();
            bool result;
            VoucherInfo voucher = new VoucherInfo();
            if (vouvher_dic.TryGetValue(ownerid, out info))
            {
                voucher.ID = voucherInfo.ID;
                voucher.OwnerID = ownerid;
                voucher.DeviceID = info.DeviceID;
                voucher.PicShow = info.PicShow;
                voucher.CardShow = info.CardShow;
                voucher.EffectiveStarttime = voucherInfo.EffectiveStarttime;
                voucher.EffectiveEndtime = voucherInfo.EffectiveEndtime;
                voucher.PicuploadFlag = info.PicuploadFlag;
                voucher.CarduploadFlag = info.CarduploadFlag;
                voucher.Lssuestate = info.Lssuestate;
                voucher.CardNO = info.CardNO;
                voucher.PicturePath = info.PicturePath;
                voucher.AuthorizedFloor = voucherInfo.AuthorizedFloor;
                voucher.AuthData = voucherInfo.AuthData;
                DateTime starttime1 = Convert.ToDateTime(info.EffectiveStarttime);
                DateTime starttime2 = Convert.ToDateTime(voucherInfo.EffectiveStarttime);
                DateTime endtime1 = Convert.ToDateTime(info.EffectiveEndtime);
                DateTime endtime2 = Convert.ToDateTime(voucherInfo.EffectiveEndtime);
                if (info.AuthorizedFloor != voucherInfo.AuthorizedFloor)
                {
                    voucher.Lssuestate = 0;
                }
                else if (DateTime.Compare(starttime1, starttime2) != 0 || DateTime.Compare(endtime1, endtime2) != 0)
                {
                    voucher.Lssuestate = 0;
                }

                result = da.UpdateVoucherByDev(voucher);
            }
            else
            {
                voucher.OwnerID = ownerid;
                voucher.DeviceID = voucherInfo.DeviceID;
                voucher.AuthorizedFloor = voucherInfo.AuthorizedFloor;
                voucher.EffectiveStarttime = voucherInfo.EffectiveStarttime;
                voucher.EffectiveEndtime = voucherInfo.EffectiveEndtime;
                voucher.PicShow = voucherInfo.PicShow;
                voucher.CardShow = voucherInfo.CardShow;
                voucher.AuthorizedFloor = voucherInfo.AuthorizedFloor;
                voucher.projectID = voucherInfo.projectID;
                voucher.AuthData = voucherInfo.AuthData;
                result = da.AddVoucher(voucher);
            }
            return result;
        }

        public ResponseMessage DelVoucher(VoucherInfo voucherInfo)
        {
            ResponseMessage message = new ResponseMessage();

            VoucherDAL da = new VoucherDAL();
            bool result = da.DeleteVoucher(voucherInfo);
            if (result)
            {
                message.errcode = 0;
            }
            else
            {
                message.errcode = 1;
                message.errmsg = "删除凭证失败";
            }

            return message;
        }

        public ResponseMessage QueryVoucher(VoucherInfo voucherInfo)
        {
            ResponseMessage message = new ResponseMessage();

            VoucherDAL da = new VoucherDAL();
            message.errcode = 0;
            message.data = da.QueryVoucherList(voucherInfo);
            message.total = da.QueryVoucherListCount(voucherInfo);

            return message;
        }

        public ResponseMessage LoadVoucher(VoucherInfo voucherInfo)
        {
            ResponseMessage message = new ResponseMessage();
            VoucherDAL da = new VoucherDAL();
            message.errcode = 0;
            message.data = da.LoadVoucher(voucherInfo.ID);

            return message;
        }

        public ResponseMessage BindCard(VoucherInfo voucherInfo, string path)
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                LssueinfoTODev lssueinfo = new LssueinfoTODev();
                lssueinfo.DeviceIP = voucherInfo.DeviceIP;
                lssueinfo.Devicetype = voucherInfo.DeviceType;
                lssueinfo.ownerID = voucherInfo.OwnerID;
                lssueinfo.devID = voucherInfo.DeviceID;
                lssueinfo.UserID = voucherInfo.UUID;
                lssueinfo.DeviceNO = voucherInfo.DeviceNO;
                lssueinfo.UserName = voucherInfo.OwnerName;
                lssueinfo.cardNO = voucherInfo.CardNO;
                lssueinfo.Authorized_floor = voucherInfo.AuthorizedFloor;
                lssueinfo.Effective_starttime = Convert.ToDateTime(voucherInfo.EffectiveStarttime);
                lssueinfo.Effective_endtime = Convert.ToDateTime(voucherInfo.EffectiveEndtime);
                lssueinfo.picpath = voucherInfo.PicturePath;
                lssueinfo.m_lUserID = voucherInfo.m_lUserID;
                lssueinfo.Success_time = DateTime.Now;
                lssueinfo.m_iDeleteType = 2;
                string errormsg = string.Empty;
                bool oneclick = false;
                CardAdd_1(lssueinfo, path, out errormsg, oneclick);
                VoucherDAL da = new VoucherDAL();
                da.UpdateCardStatus(lssueinfo.ownerID, lssueinfo.devID, errormsg);
            }
            catch
            {
                message.errcode = 1;
                message.errmsg = "卡号绑定异常";
            }
            return message;
        }

        public ResponseMessage BindHead(VoucherInfo voucherInfo, string path)
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                LssueinfoTODev lssueinfo = new LssueinfoTODev();
                lssueinfo.DeviceIP = voucherInfo.DeviceIP;
                lssueinfo.Devicetype = voucherInfo.DeviceType;
                lssueinfo.ownerID = voucherInfo.OwnerID;
                lssueinfo.devID = voucherInfo.DeviceID;
                lssueinfo.UserID = voucherInfo.UUID;
                lssueinfo.DeviceNO = voucherInfo.DeviceNO;
                lssueinfo.UserName = voucherInfo.OwnerName;
                lssueinfo.cardNO = voucherInfo.CardNO;
                lssueinfo.Authorized_floor = voucherInfo.AuthorizedFloor;
                lssueinfo.Effective_starttime = Convert.ToDateTime(voucherInfo.EffectiveStarttime);
                lssueinfo.Effective_endtime = Convert.ToDateTime(voucherInfo.EffectiveEndtime);
                lssueinfo.picpath = voucherInfo.PicturePath;
                lssueinfo.m_lUserID = voucherInfo.m_lUserID;
                lssueinfo.Success_time = DateTime.Now;
                lssueinfo.m_iDeleteType = 2;
                FaceAdd(lssueinfo, path);
            }
            catch
            {
                message.errcode = 1;
                message.errmsg = "头像绑定异常";
            }
            return message;
        }
        public ResponseMessage PersonAdd(VoucherInfo voucherInfo, string path)
        {
            ResponseMessage message = new ResponseMessage();

            LssueinfoTODev lssueinfo = new LssueinfoTODev();
            lssueinfo.DeviceIP = voucherInfo.DeviceIP;
            lssueinfo.Devicetype = voucherInfo.DeviceType;
            lssueinfo.ownerID = voucherInfo.OwnerID;
            lssueinfo.devID = voucherInfo.DeviceID;
            lssueinfo.UserID = voucherInfo.UUID;
            lssueinfo.DeviceNO = voucherInfo.DeviceNO;
            lssueinfo.UserName = voucherInfo.OwnerName;
            lssueinfo.cardNO = voucherInfo.CardNO;
            lssueinfo.Authorized_floor = voucherInfo.AuthorizedFloor;
            lssueinfo.Effective_starttime = Convert.ToDateTime(voucherInfo.EffectiveStarttime);
            lssueinfo.Effective_endtime = Convert.ToDateTime(voucherInfo.EffectiveEndtime);
            lssueinfo.picpath = voucherInfo.PicturePath;
            lssueinfo.m_lUserID = voucherInfo.m_lUserID;
            lssueinfo.Success_time = DateTime.Now;
            lssueinfo.m_iDeleteType = 2;
            bool onclick = true;
            string errormsg = string.Empty;
            PersonAdd_3(lssueinfo, path, out errormsg, onclick);
            VoucherDAL da = new VoucherDAL();
            da.UpdateVoucherState(voucherInfo.OwnerID, voucherInfo.DeviceID, errormsg);

            return message;
        }

        public ResponseMessage PersonAddSingle(VoucherInfo voucherInfo, string path)
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                LssueinfoTODev lssueinfo = new LssueinfoTODev();
                lssueinfo.DeviceIP = voucherInfo.DeviceIP;
                lssueinfo.Devicetype = voucherInfo.DeviceType;
                lssueinfo.ownerID = voucherInfo.OwnerID;
                lssueinfo.devID = voucherInfo.DeviceID;
                lssueinfo.UserID = voucherInfo.UUID;
                lssueinfo.DeviceNO = voucherInfo.DeviceNO;
                lssueinfo.UserName = voucherInfo.OwnerName;
                lssueinfo.cardNO = voucherInfo.CardNO;
                lssueinfo.Authorized_floor = voucherInfo.AuthorizedFloor;
                lssueinfo.Effective_starttime = Convert.ToDateTime(voucherInfo.EffectiveStarttime);
                lssueinfo.Effective_endtime = Convert.ToDateTime(voucherInfo.EffectiveEndtime);
                lssueinfo.picpath = voucherInfo.PicturePath;
                lssueinfo.m_lUserID = voucherInfo.m_lUserID;
                lssueinfo.Success_time = DateTime.Now;
                lssueinfo.m_iDeleteType = 2;
                bool onclick = false;
                string errormsg = string.Empty;
                PersonAdd_3(lssueinfo, path, out errormsg, onclick);
                VoucherDAL da = new VoucherDAL();
                da.UpdateVoucherState(voucherInfo.OwnerID, voucherInfo.DeviceID, errormsg);
            }
            catch
            {
                message.errcode = 1;
                message.errmsg = "下发凭证异常";
            }
            return message;
        }

        #region 绑定卡号

        public int CardAdd_1(LssueinfoTODev Lssueinfo, string path, out string errormsg, bool OneClick)
        {
            DevicesGoto CardCound = new DevicesGoto();
            int CCount = CardCound.GetAllCardCount(Lssueinfo.m_lUserID, Lssueinfo.UserID);
            // 业主数据库下已捆绑了卡号
            if (Lssueinfo.cardNO != null)
            {
                //判断设备上该用户是否已经绑定卡号（大于0张卡）
                //已绑定不处理

                //未绑定，先删除再新增绑定卡号

                if (CCount == 0)//该业主下无绑定卡
                {
                    //重新查询设备总的卡数量
                    CCount = CardCound.GetAllCardCount(Lssueinfo.m_lUserID, "");
                    if (CCount >= 6000)
                    {
                        errormsg = "超出设备卡存储最大量";
                        //超出设备存储最大量，不允许添加
                        return 1;
                    }
                }
                else
                {
                    bool result = DeleteCardInfo_1(Lssueinfo);//先删除该工号下所有卡
                }

                m_iCardInfoRecordIndex = 0;
                if (-1 != m_lCardInfoRecordHandle)
                {
                    if (CHCNetSDK.NET_DVR_StopRemoteConfig(m_lCardInfoRecordHandle))
                    {
                        m_lCardInfoRecordHandle = -1;
                    }
                }

                g_fCardInfoRecordCallback = new CHCNetSDK.RemoteConfigCallback(ProcessCardInfoRecordCallback);
                string sURL = "POST /ISAPI/AccessControl/CardInfo/Record?format=json";
                IntPtr ptrURL = Marshal.StringToHGlobalAnsi(sURL);

                m_lCardInfoRecordHandle = CHCNetSDK.NET_DVR_StartRemoteConfig(Lssueinfo.m_lUserID, CHCNetSDK.NET_DVR_JSON_CONFIG, ptrURL, sURL.Length, g_fCardInfoRecordCallback);
                if (-1 == m_lCardInfoRecordHandle)
                {
                    errormsg = "远程配置失败，错误代码:" + CHCNetSDK.NET_DVR_GetLastError();
                    string strTemp = string.Format("Card Info Record Fail,Error Code={0}", CHCNetSDK.NET_DVR_GetLastError());
                    Marshal.FreeHGlobal(ptrURL);

                    return 2;
                }

                Marshal.FreeHGlobal(ptrURL);
                if (!SendCardInfo(Lssueinfo, path, OneClick))
                {
                    CHCNetSDK.NET_DVR_StopRemoteConfig(m_lCardInfoRecordHandle);
                    m_lCardInfoRecordHandle = -1;
                }

            }
            errormsg = "";
            return 0;
        }

        private bool SendCardInfo(LssueinfoTODev Lssueinfo, string path, bool OneClick)
        {
            if (-1 == m_lCardInfoRecordHandle)
            {
                return false;
            }

            //if (m_iCardInfoRecordIndex >= m_iCardCount)
            //{
            //    return false;
            //}

            CCardInfoRecord JsonCardInfoRecord = new CCardInfoRecord();
            JsonCardInfoRecord.CardInfo = new CCardInfoContent();

            JsonCardInfoRecord.CardInfo.employeeNo = Lssueinfo.UserID;//EmployeeNo;//工号
            JsonCardInfoRecord.CardInfo.cardNo = Lssueinfo.cardNO;// CardNO;//卡号
            JsonCardInfoRecord.CardInfo.cardType = "normalCard";
            JsonCardInfoRecord.CardInfo.leaderCard = "";

            string strCardInfoRecord = JsonConvert.SerializeObject(JsonCardInfoRecord);

            IntPtr ptrCardInfoRecord = Marshal.StringToHGlobalAnsi(strCardInfoRecord);

            if (!CHCNetSDK.NET_DVR_SendRemoteConfig(m_lCardInfoRecordHandle, (int)CHCNetSDK.LONG_CFG_SEND_DATA_TYPE_ENUM.ENUM_SEND_JSON_DATA, ptrCardInfoRecord, (uint)strCardInfoRecord.Length))
            {//error
                Marshal.FreeHGlobal(ptrCardInfoRecord);
                return false;
            }
            Marshal.FreeHGlobal(ptrCardInfoRecord);
            m_iCardInfoRecordIndex++;
            if (OneClick)
            {
                if (Lssueinfo.picpath != null)
                {
                    FaceAdd(Lssueinfo, path);
                }
            }

            return true;
        }

        private void ProcessCardInfoRecordCallback(uint dwType, IntPtr lpBuffer, uint dwBufLen, IntPtr pUserData)
        {
            if (pUserData == null)
            {
                return;
            }
            if (dwType == (uint)CHCNetSDK.NET_SDK_CALLBACK_TYPE.NET_SDK_CALLBACK_TYPE_STATUS)
            {
                uint dwStatus = (uint)Marshal.ReadInt32(lpBuffer);
                if (dwStatus == (uint)CHCNetSDK.NET_SDK_CALLBACK_STATUS_NORMAL.NET_SDK_CALLBACK_STATUS_FAILED)
                {
                    DefWndProc(1001, 1);
                    //CHCNetSDK.PostMessage(pUserData, 1001, 1, 0);
                    //可以结束了，异常结束
                }
                else if (dwStatus == (uint)CHCNetSDK.NET_SDK_CALLBACK_STATUS_NORMAL.NET_SDK_CALLBACK_STATUS_EXCEPTION)
                {
                    DefWndProc(1001, 2);
                    //CHCNetSDK.PostMessage(pUserData, 1001, 2, 0);
                    //可以结束了，异常结束
                }
                else if (dwStatus == (uint)CHCNetSDK.NET_SDK_CALLBACK_STATUS_NORMAL.NET_SDK_CALLBACK_STATUS_PROCESSING)
                {
                    ;
                }
                else
                {
                    DefWndProc(1001, 3);
                    //CHCNetSDK.PostMessage(pUserData, 1001, 3, 0);
                    //可以结束了，异常结束
                }
            }
            else if (dwType == (uint)CHCNetSDK.NET_SDK_CALLBACK_TYPE.NET_SDK_CALLBACK_TYPE_DATA)
            {
                //输出上一包解析信息, 1003
                string strResponseStatus = Marshal.PtrToStringAnsi(lpBuffer);
                CResponseStatus JsonResponseStatus = new CResponseStatus();
                JsonResponseStatus = JsonConvert.DeserializeObject<CResponseStatus>(strResponseStatus);
                DefWndProc(1003, JsonResponseStatus.statusCode);
                //CHCNetSDK.PostMessage(pUserData, 1003, JsonResponseStatus.statusCode, 0);
                //return;
                //JsonResponseStatus.statusCode=1为成功，否则为失败，添加处理过程
                //if (m_iCardInfoRecordIndex >= m_iCardCount)
                //{
                //    DefWndProc(1001, 4);
                //    CHCNetSDK.PostMessage(pUserData, 1001, 4, 0);
                //    //可以结束了，正常(异常)结束
                //    return;
                //}
                //DefWndProc(1002, 0);
                //CHCNetSDK.PostMessage(pUserData, 1002, 0, 0);
                //在主线程中发送下一个用户
            }
            return;
        }

        private void DefWndProc(int MessageID, int ErrorCode)
        {
            switch (MessageID)
            {
                case 1001:
                    int iErrorMsg = ErrorCode;
                    if (iErrorMsg == 1)
                    {
                        //ListViewItem listItem = new ListViewItem();
                        //listItem.Text = "Fail";
                        string strTemp = string.Format("NET_SDK_CALLBACK_STATUS_FAILED");
                        //listItem.SubItems.Add(strTemp);
                        //this.AddList(listViewMessage, listItem);
                    }
                    else if (iErrorMsg == 2)
                    {
                        //ListViewItem listItem = new ListViewItem();
                        //listItem.Text = "Fail";
                        string strTemp = string.Format("NET_SDK_CALLBACK_STATUS_EXCEPTION");
                        //listItem.SubItems.Add(strTemp);
                        //this.AddList(listViewMessage, listItem);
                    }
                    else if (iErrorMsg == 3)
                    {
                        //ListViewItem listItem = new ListViewItem();
                        //listItem.Text = "Fail";
                        string strTemp = string.Format("NET_SDK_CALLBACK_OTHER_ERROR");
                        //listItem.SubItems.Add(strTemp);
                        //this.AddList(listViewMessage, listItem);
                    }
                    else if (iErrorMsg == 4)
                    {
                        //ListViewItem listItem = new ListViewItem();
                        //listItem.Text = "Succ";
                        string strTemp = string.Format("NET_SDK_CALLBACK_FINISH");
                        //listItem.SubItems.Add(strTemp);
                        //this.AddList(listViewMessage, listItem);
                    }
                    if (-1 != m_lCardInfoRecordHandle)
                    {
                        if (CHCNetSDK.NET_DVR_StopRemoteConfig(m_lCardInfoRecordHandle))
                        {
                            m_lCardInfoRecordHandle = -1;
                        }
                    }
                    break;
                case 1002:
                    ////SendCardInfo();
                    break;
                case 1003:
                    int iError = ErrorCode;
                    if (iError == 1)
                    {
                        //ListViewItem listItem = new ListViewItem();
                        //listItem.Text = "Succ";
                        string strTemp = string.Format("Send Success");
                        //listItem.SubItems.Add(strTemp);
                        //this.AddList(listViewMessage, listItem);
                    }
                    else
                    {
                        //ListViewItem listItem = new ListViewItem();
                        //listItem.Text = "Fail";
                        string strTemp = string.Format("Send Failed");
                        //listItem.SubItems.Add(strTemp);
                        //this.AddList(listViewMessage, listItem);
                    }
                    break;
                case 1004:
                    int iErrorSer = ErrorCode;
                    if (iErrorSer == 1)
                    {
                        //ListViewItem listItem = new ListViewItem();
                        //listItem.Text = "Fail";
                        string strTemp = string.Format("NET_SDK_CALLBACK_STATUS_FAILED");
                        //listItem.SubItems.Add(strTemp);
                        //this.AddList(listViewMessage, listItem);
                    }
                    else if (iErrorSer == 2)
                    {
                        //ListViewItem listItem = new ListViewItem();
                        //listItem.Text = "Fail";
                        string strTemp = string.Format("NET_SDK_CALLBACK_STATUS_EXCEPTION");
                        //listItem.SubItems.Add(strTemp);
                        //this.AddList(listViewMessage, listItem);
                    }
                    else if (iErrorSer == 3)
                    {
                        //ListViewItem listItem = new ListViewItem();
                        //listItem.Text = "Fail";
                        string strTemp = string.Format("NET_SDK_CALLBACK_OTHER_ERROR");
                        //listItem.SubItems.Add(strTemp);
                        //this.AddList(listViewMessage, listItem);
                    }
                    else if (iErrorSer == 4)
                    {
                        //ListViewItem listItem = new ListViewItem();
                        //listItem.Text = "Succ";
                        string strTemp = string.Format("NET_SDK_CALLBACK_FINISH");
                        //listItem.SubItems.Add(strTemp);
                        //this.AddList(listViewMessage, listItem);
                    }
                    if (-1 != m_lCardInfoSearchHandle)
                    {
                        if (CHCNetSDK.NET_DVR_StopRemoteConfig(m_lCardInfoSearchHandle))
                        {
                            m_lCardInfoSearchHandle = -1;
                        }
                    }
                    break;
                case 1005:
                    //SearchCardInfo();
                    break;

                case 1006:
                    //int EmployeeNoCount1 = m_JsonCardInfoSearch.CardInfoSearch.numOfMatches;
                    EmployeeNoCount = 1;
                    //break;
                    //for (int i = 0; i < m_JsonCardInfoSearch.CardInfoSearch.numOfMatches; i++)
                    //{
                    //    //    listViewCardManage.BeginUpdate();

                    //    //    ListViewItem listItem = new ListViewItem();
                    //    //    listItem.Text = (m_iCardCount + 1).ToString();
                    //    //    listItem.SubItems.Add(m_JsonCardInfoSearch.CardInfoSearch.CardInfo[i].employeeNo.ToString());
                    //    if (m_JsonCardInfoSearch.CardInfoSearch.CardInfo[i].cardNo != null)
                    //    {
                    //        EmployeeNoCount = 1;
                    //        EmployeeNoCount = 1;
                    //        //        listItem.SubItems.Add(m_JsonCardInfoSearch.CardInfoSearch.CardInfo[i].cardNo);
                    //    }
                    //}
                    break;
                    //    else
                    //    {
                    //        listItem.SubItems.Add("");
                    //    }
                    //    if (m_JsonCardInfoSearch.CardInfoSearch.CardInfo[i].cardType != null)
                    //    {
                    //        listItem.SubItems.Add(m_JsonCardInfoSearch.CardInfoSearch.CardInfo[i].cardType);
                    //    }
                    //    else
                    //    {
                    //        listItem.SubItems.Add("");
                    //    }
                    //    if (m_JsonCardInfoSearch.CardInfoSearch.CardInfo[i].leaderCard != null)
                    //    {
                    //        listItem.SubItems.Add(m_JsonCardInfoSearch.CardInfoSearch.CardInfo[i].leaderCard);
                    //    }
                    //    else
                    //    {
                    //        listItem.SubItems.Add("");
                    //    }

                    //    listViewCardManage.Items.Add(listItem);
                    //    listViewCardManage.EndUpdate();

                    //    m_iCardCount += 1;
            }
            //break;
            //default:
            //    base.DefWndProc(ref m);
            //    break;

        }

        public class CEmployeeNoList
        {
            public string employeeNo { get; set; }
        }
        public class CCardInfoDelCond
        {
            public CCardInfoDelCondContent CardInfoDelCond { get; set; }
        }
        public class CCardInfoDelCondContent
        {
            public List<CEmployeeNoList> EmployeeNoList { get; set; }
            //public List<CCardNoList> CardNoList { get; set; }//需要关联卡号时启用，负责会造成数据错误，把所有卡都删除
        }
        public class CResponseStatus
        {
            public string requestURL { get; set; }
            public int statusCode { get; set; }
            public string statusString { get; set; }
            public string subStatusCode { get; set; }
            public int errorCode { get; set; }
            public string errorMsg { get; set; }
            public string FPID { get; set; }
        }
        public class CCardInfoRecord
        {
            public CCardInfoContent CardInfo { get; set; }
        }

        public class CCardInfoContent
        {
            public string employeeNo { get; set; }
            public string cardNo { get; set; }
            public string cardType { get; set; }
            public string leaderCard { get; set; }
        }

        public bool DeleteCardInfo_1(LssueinfoTODev Lssueinfo)
        {
            //NET_DVR_Init();
            //DevicesConnect(DevicesIP);
            //int m_iDeleteType = 1;
            IntPtr ptrOutBuf = Marshal.AllocHGlobal(1024);
            IntPtr ptrStatusBuffer = Marshal.AllocHGlobal(1024);

            for (int i = 0; i < 1024; i++)
            {
                Marshal.WriteByte(ptrOutBuf, i, 0);
                Marshal.WriteByte(ptrStatusBuffer, i, 0);
            }

            CHCNetSDK.NET_DVR_XML_CONFIG_INPUT struInput = new CHCNetSDK.NET_DVR_XML_CONFIG_INPUT();
            CHCNetSDK.NET_DVR_XML_CONFIG_OUTPUT struOuput = new CHCNetSDK.NET_DVR_XML_CONFIG_OUTPUT();

            string sUrl = "PUT /ISAPI/AccessControl/CardInfo/Delete?format=json";
            IntPtr ptrURL = Marshal.StringToHGlobalAnsi(sUrl);
            struInput.dwSize = (uint)Marshal.SizeOf(struInput);
            struInput.lpRequestUrl = ptrURL;
            struInput.dwRequestUrlLen = (uint)sUrl.Length;
            struInput.dwRecvTimeOut = 60000;

            CCardInfoDelCond JsonCardInfoDelCond = new CCardInfoDelCond();
            JsonCardInfoDelCond.CardInfoDelCond = new CCardInfoDelCondContent();
            JsonCardInfoDelCond.CardInfoDelCond.EmployeeNoList = new List<CEmployeeNoList>();
            //JsonCardInfoDelCond.CardInfoDelCond.CardNoList = new List<CCardNoList>();

            ////if (Lssueinfo.m_iDeleteType == 1)
            ////{

            CEmployeeNoList singleEmployeeNoList = new CEmployeeNoList();
            singleEmployeeNoList.employeeNo = Lssueinfo.UserID;//"341";
            JsonCardInfoDelCond.CardInfoDelCond.EmployeeNoList.Add(singleEmployeeNoList);

            ////}
            ////else if (Lssueinfo.m_iDeleteType == 2)
            ////{

            //CCardNoList singleCardNoList = new CCardNoList();
            //singleCardNoList.cardNo = Lssueinfo.cardNO;//"1111";
            //JsonCardInfoDelCond.CardInfoDelCond.CardNoList.Add(singleCardNoList);

            ////}

            string strCardInfoDelCond = JsonConvert.SerializeObject(JsonCardInfoDelCond);

            IntPtr ptrInBuffer = Marshal.StringToHGlobalAnsi(strCardInfoDelCond);

            struInput.lpInBuffer = ptrInBuffer;
            struInput.dwInBufferSize = (uint)strCardInfoDelCond.Length;

            struOuput.dwSize = (uint)Marshal.SizeOf(struOuput);
            struOuput.lpOutBuffer = ptrOutBuf;
            struOuput.dwOutBufferSize = 1024;
            struOuput.lpStatusBuffer = ptrStatusBuffer;
            struOuput.dwStatusSize = 1024;

            IntPtr ptrInput = Marshal.AllocHGlobal(Marshal.SizeOf(struInput));
            Marshal.StructureToPtr(struInput, ptrInput, false);
            IntPtr ptrOuput = Marshal.AllocHGlobal(Marshal.SizeOf(struOuput));
            Marshal.StructureToPtr(struOuput, ptrOuput, false);
            if (!CHCNetSDK.NET_DVR_STDXMLConfig(Lssueinfo.m_lUserID, ptrInput, ptrOuput))
            {
                //ListViewItem listItem = new ListViewItem();
                //listItem.Text = "Fail";
                //string strTemp = string.Format("Delete Card Info Fail,Error Code={0}", CHCNetSDK.NET_DVR_GetLastError());
                //listItem.SubItems.Add(strTemp);
                //this.AddList(listViewMessage, listItem);
                Marshal.FreeHGlobal(ptrOutBuf);
                Marshal.FreeHGlobal(ptrStatusBuffer);
                Marshal.FreeHGlobal(ptrInBuffer);
                Marshal.FreeHGlobal(ptrInput);
                Marshal.FreeHGlobal(ptrOuput);
                Marshal.FreeHGlobal(ptrURL);
                return false;
            }
            else
            {
                //ListViewItem listItem = new ListViewItem();
                //listItem.Text = "Succ";
                //string strTemp = string.Format("Delete Card Info Success");
                //listItem.SubItems.Add(strTemp);
                //this.AddList(listViewMessage, listItem);

                string strResponseStatus = Marshal.PtrToStringAnsi(struOuput.lpOutBuffer);
                CResponseStatus JsonResponseStatus = new CResponseStatus();
                JsonResponseStatus = JsonConvert.DeserializeObject<CResponseStatus>(strResponseStatus);
                Marshal.FreeHGlobal(ptrOutBuf);
                Marshal.FreeHGlobal(ptrStatusBuffer);
                Marshal.FreeHGlobal(ptrInBuffer);
                Marshal.FreeHGlobal(ptrInput);
                Marshal.FreeHGlobal(ptrOuput);
                Marshal.FreeHGlobal(ptrURL);
                return true;
            }


        }//按工号删除指定卡号或所有该工号下的卡

        #endregion

        #region 下发至梯控面板

        public bool PersonAdd_3(LssueinfoTODev Lssueinfo, string path, out string errormsg, bool OneClick)//下发业主信息至梯控面板设备端，包括DeviceIP、m_lUserID、UserID、ownerName、cardNO、Authorized_floor、Effective_starttime、Effective_endtime、picpath、Success_time
        {
            m_iUserInfoRecordIndex = 0;
            if (-1 != m_lUserInfoRecordHandle)
            {
                if (CHCNetSDK.NET_DVR_StopRemoteConfig(m_lUserInfoRecordHandle))
                {
                    m_lUserInfoRecordHandle = -1;
                }
                errormsg = "设备不在线";
                return false;
            }
            string sURL = "PUT /ISAPI/AccessControl/UserInfo/SetUp?format=json";
            IntPtr ptrURL = Marshal.StringToHGlobalAnsi(sURL);
            m_lSetUserCfgHandle = CHCNetSDK.NET_DVR_StartRemoteConfig(Lssueinfo.m_lUserID, CHCNetSDK.NET_DVR_JSON_CONFIG, ptrURL, sURL.Length, null);
            if (m_lSetUserCfgHandle < 0)
            {
                errormsg = "设备远程配置失败";
                Marshal.FreeHGlobal(ptrURL);
                return false;
            }
            else
            {
                SendUserInfo1(Lssueinfo, out errormsg);
                Marshal.FreeHGlobal(ptrURL);

                if (OneClick)
                {
                    //卡号不为空的时候下发卡
                    if (Lssueinfo.cardNO != null)
                    {
                        string msg = string.Empty;
                        CardAdd_1(Lssueinfo, path, out msg, OneClick);
                        VoucherDAL da = new VoucherDAL();
                        da.UpdateCardStatus(Lssueinfo.ownerID, Lssueinfo.devID, msg);
                    }
                }

                return true;
            }
        }


        private bool SendUserInfo1(LssueinfoTODev Lssueinfo, out string errormsg)
        {
            //CUserInfoRecord JsonUserInfo = new CUserInfoRecord();
            //JsonUserInfo.UserInfo = new CUserInfoContent();
            //JsonUserInfo.UserInfo.employeeNo = textBoxEmployeeNo.Text;
            //JsonUserInfo.UserInfo.name = textBoxName.Text;
            //JsonUserInfo.UserInfo.userType = "normal";
            //JsonUserInfo.UserInfo.Valid = new CValid();
            //JsonUserInfo.UserInfo.Valid.enable = true;
            //JsonUserInfo.UserInfo.Valid.beginTime = "2017-08-01T17:30:08";
            //JsonUserInfo.UserInfo.Valid.endTime = "2037-12-12T23:59:59";
            //JsonUserInfo.UserInfo.Valid.timeType = "local";

            //JsonUserInfo.UserInfo.doorRight = "1";
            //JsonUserInfo.UserInfo.RightPlan = new List<CRightPlan>();
            //CRightPlan JsonRightPlan = new CRightPlan();
            //JsonRightPlan.doorNo = 1;
            //JsonRightPlan.planTemplateNo = textBoxRightPlan.Text;
            //JsonUserInfo.UserInfo.RightPlan.Add(JsonRightPlan);
            //     JsonUserInfo.UserInfo.userVerifyMode = "face";
            CUserInfoRecord JsonUserInfoRecord = new CUserInfoRecord();
            JsonUserInfoRecord.UserInfo = new CUserInfoContent();
            JsonUserInfoRecord.UserInfo.Valid = new CVaild();
            JsonUserInfoRecord.UserInfo.RightPlan = new List<CRightPlan>();
            JsonUserInfoRecord.UserInfo.closeDelayEnabled = false;

            JsonUserInfoRecord.UserInfo.Valid.enable = true;
            Random employeeNoR = new Random();
            //string Rnd=employeeNoR.Next(20,10000).ToString();
            JsonUserInfoRecord.UserInfo.employeeNo = Lssueinfo.UserID; //Rnd ;//工号
            JsonUserInfoRecord.UserInfo.name = Lssueinfo.UserName;//"test" + Rnd;//姓名
            JsonUserInfoRecord.UserInfo.userType = "normal";//类型
            JsonUserInfoRecord.UserInfo.Valid.beginTime = Lssueinfo.Effective_starttime.ToString("s");//"2017-08-01T17:30:08";//有效起始时间
            JsonUserInfoRecord.UserInfo.Valid.endTime = Lssueinfo.Effective_endtime.ToString("s");//"2020-08-01T17:30:08";//有效结束时间
            JsonUserInfoRecord.UserInfo.password = "123456";
            JsonUserInfoRecord.UserInfo.belongGroup = "";
            JsonUserInfoRecord.UserInfo.doorRight = "1";
            string sRightPlan = "Door1:1-";
            int iDoorNoBegin = 0;
            int iDoorNoEnd = 0;
            int iPlanTemplateBegin = 0;
            int iPlanTemplateEnd = 0;
            for (int iCurrentLocate = 0; iCurrentLocate < sRightPlan.Length - 1;)
            {
                if (sRightPlan.IndexOf("Door", iCurrentLocate) != -1)
                {
                    iDoorNoBegin = sRightPlan.IndexOf("Door", iCurrentLocate) + 4;
                    iDoorNoEnd = sRightPlan.IndexOf(":", iCurrentLocate) - 1;
                    iPlanTemplateBegin = sRightPlan.IndexOf(":", iCurrentLocate) + 1;
                    iPlanTemplateEnd = sRightPlan.IndexOf("-", iCurrentLocate) - 1;
                    iCurrentLocate = sRightPlan.IndexOf("-", iCurrentLocate) + 1;
                    int iDoorNo = 0;
                    int.TryParse(sRightPlan.Substring(iDoorNoBegin, (iDoorNoEnd - iDoorNoBegin + 1)), out iDoorNo);
                    CRightPlan singleRightPlan = new CRightPlan();
                    singleRightPlan.doorNo = iDoorNo;
                    singleRightPlan.planTemplateNo = sRightPlan.Substring(iPlanTemplateBegin, (iPlanTemplateEnd - iPlanTemplateBegin + 1));
                    JsonUserInfoRecord.UserInfo.RightPlan.Add(singleRightPlan);
                }
                else
                {
                    break;
                }
            }
            JsonUserInfoRecord.UserInfo.maxOpenDoorTime = 0;
            JsonUserInfoRecord.UserInfo.roomNumber = 0;
            JsonUserInfoRecord.UserInfo.floorNumber = 0;
            JsonUserInfoRecord.UserInfo.doubleLockRight = false;
            JsonUserInfoRecord.UserInfo.alwaysOpenRight = false;
            JsonUserInfoRecord.UserInfo.localUIRight = false;
            JsonUserInfoRecord.UserInfo.userVerifyMode = "cardOrFace";//验证模式为刷卡或人脸
            JsonUserInfoRecord.UserInfo.Valid.timeType = "local";
            JsonUserInfoRecord.UserInfo.openDoorTime = 0;



            string strJsonUserInfo = JsonConvert.SerializeObject(JsonUserInfoRecord, Formatting.Indented,
                                                        new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore });

            byte[] byJsonUserInfo = System.Text.Encoding.UTF8.GetBytes(strJsonUserInfo);
            IntPtr ptrJsonUserInfo = Marshal.AllocHGlobal(byJsonUserInfo.Length);
            Marshal.Copy(byJsonUserInfo, 0, ptrJsonUserInfo, byJsonUserInfo.Length);

            IntPtr ptrJsonData = Marshal.AllocHGlobal(1024);
            for (int i = 0; i < 1024; i++)
            {
                Marshal.WriteByte(ptrJsonData, i, 0);
            }

            int dwState = (int)CHCNetSDK.NET_SDK_SENDWITHRECV_STATUS.NET_SDK_CONFIG_STATUS_SUCCESS;
            uint dwReturned = 0;
            while (true)
            {
                dwState = CHCNetSDK.NET_DVR_SendWithRecvRemoteConfig(m_lSetUserCfgHandle, ptrJsonUserInfo, (uint)byJsonUserInfo.Length, ptrJsonData, 1024, ref dwReturned);
                string strJsonData = Marshal.PtrToStringAnsi(ptrJsonData);
                if (dwState == (int)CHCNetSDK.NET_SDK_SENDWITHRECV_STATUS.NET_SDK_CONFIG_STATUS_NEEDWAIT)
                {
                    Thread.Sleep(10);
                    continue;
                    return false;
                }
                else if (dwState == (int)CHCNetSDK.NET_SDK_SENDWITHRECV_STATUS.NET_SDK_CONFIG_STATUS_FAILED)
                {
                    errormsg = "配置失败，错误代码:" + CHCNetSDK.NET_DVR_GetLastError();
                    //MessageBox.Show("Set User Fail error:" + CHCNetSDK.NET_DVR_GetLastError());
                    return false;
                    break;
                }
                else if (dwState == (int)CHCNetSDK.NET_SDK_SENDWITHRECV_STATUS.NET_SDK_CONFIG_STATUS_SUCCESS)
                {
                    //返回NET_SDK_CONFIG_STATUS_SUCCESS代表流程走通了，但并不代表下发成功，比如有些设备可能因为人员已存在等原因下发失败，所以需要解析Json报文
                    CResponseStatus JsonResponseStatus = new CResponseStatus();
                    JsonResponseStatus = JsonConvert.DeserializeObject<CResponseStatus>(strJsonData);

                    if (JsonResponseStatus.statusCode == 1)
                    {
                        //MessageBox.Show("Set User Success123");
                    }
                    else
                    {
                        errormsg = "业主下发失败，状态码:" + JsonResponseStatus.statusCode;
                        //MessageBox.Show("Set User Fail, ResponseStatus.statusCode" + JsonResponseStatus.statusCode);
                    }
                    break;
                }
                else if (dwState == (int)CHCNetSDK.NET_SDK_SENDWITHRECV_STATUS.NET_SDK_CONFIG_STATUS_FINISH)
                {
                    //下发人员时：dwState其实不会走到这里，因为设备不知道我们会下发多少个人，所以长连接需要我们主动关闭
                    //MessageBox.Show("Set User Finish");
                    break;
                }
                else if (dwState == (int)CHCNetSDK.NET_SDK_SENDWITHRECV_STATUS.NET_SDK_CONFIG_STATUS_EXCEPTION)
                {
                    errormsg = "配置异常，错误代码:" + CHCNetSDK.NET_DVR_GetLastError();
                    //MessageBox.Show("Set User Exception error:" + CHCNetSDK.NET_DVR_GetLastError());
                    break;
                }
                else
                {
                    errormsg = "未知异常，错误代码:" + CHCNetSDK.NET_DVR_GetLastError();
                    //MessageBox.Sh/*o*/w("unknown Status error:" + CHCNetSDK.NET_DVR_GetLastError());
                    break;
                }
            }
            if (m_lSetUserCfgHandle != -1)
            {
                if (CHCNetSDK.NET_DVR_StopRemoteConfig(m_lSetUserCfgHandle))
                {
                    m_lSetUserCfgHandle = -1;
                }
            }
            Marshal.FreeHGlobal(ptrJsonUserInfo);
            Marshal.FreeHGlobal(ptrJsonData);
            errormsg = string.Empty;
            return true;
        }
        public class CUserInfoRecord
        {
            public CUserInfoContent UserInfo { get; set; }
        }

        public class CUserInfoContent
        {
            public string employeeNo { get; set; }
            public string name { get; set; }
            public string userType { get; set; }
            public bool closeDelayEnabled { get; set; }
            public CVaild Valid { get; set; }
            public string belongGroup { get; set; }
            public string password { get; set; }
            public string doorRight { get; set; }
            public List<CRightPlan> RightPlan { get; set; }
            public int maxOpenDoorTime { get; set; }
            public int openDoorTime { get; set; }
            public int roomNumber { get; set; }
            public int floorNumber { get; set; }
            public bool doubleLockRight { get; set; }
            public bool alwaysOpenRight { get; set; }
            public bool localUIRight { get; set; }
            public string userVerifyMode { get; set; }
        }

        public class CUserInfoSearch
        {
            public CUserInfoSearchContent UserInfoSearch { get; set; }
        }

        public class CUserInfoSearchContent
        {
            public string searchID { get; set; }
            public string responseStatusStrg { get; set; }
            public int numOfMatches { get; set; }
            public int totalMatches { get; set; }
            public List<CUserInfoContent> UserInfo { get; set; }
        }


        public class CVaild
        {
            public bool enable { get; set; }
            public string beginTime { get; set; }
            public string endTime { get; set; }
            public string timeType { get; set; }
        }

        public class CRightPlan
        {
            public int doorNo { get; set; }
            public string planTemplateNo { get; set; }
        }

        #endregion

        #region 绑定头像
        public bool FaceAdd(LssueinfoTODev Lssueinfo, string path)//新增人脸,传入m_lUserID\UserID\
        {
            //NET_DVR_Init();
            //DevicesConnect(DevicesIP);
            DevicesGoto CardCound = new DevicesGoto();
            int CCount = CardCound.FaceGetByFDID(Lssueinfo.m_lUserID);
            if (CCount >= 5000)//该设备头像存储已满
            {
                return false;
            }

            m_iFaceDataRecordIndex = 0;
            if (-1 != m_lFaceDataRecordHandle)
            {
                if (CHCNetSDK.NET_DVR_StopRemoteConfig(m_lFaceDataRecordHandle))
                {
                    m_lFaceDataRecordHandle = -1;
                }
            }

            g_fFaceDataRecordCallback = new CHCNetSDK.RemoteConfigCallback(ProcessFaceDataRecordCallback);
            string sURL = "POST /ISAPI/Intelligent/FDLib/FaceDataRecord?format=json";
            IntPtr ptrURL = Marshal.StringToHGlobalAnsi(sURL);

            m_lFaceDataRecordHandle = CHCNetSDK.NET_DVR_StartRemoteConfig(Lssueinfo.m_lUserID, CHCNetSDK.NET_DVR_FACE_DATA_RECORD, ptrURL, sURL.Length, g_fFaceDataRecordCallback);
            if (-1 == m_lFaceDataRecordHandle)
            {
                string strTemp = string.Format("Face Data Record Fail,Error Code={0}", CHCNetSDK.NET_DVR_GetLastError());
                Marshal.FreeHGlobal(ptrURL);
                return false;
            }

            Marshal.FreeHGlobal(ptrURL);
            string errormsg = string.Empty;
            if (!SendFaceRecord(Lssueinfo, path, out errormsg))
            {
                CHCNetSDK.NET_DVR_StopRemoteConfig(m_lFaceDataRecordHandle);
                m_lFaceDataRecordHandle = -1;
            }
            VoucherDAL da = new VoucherDAL();
            da.UpdateFaceStatus(Lssueinfo.ownerID, Lssueinfo.devID, errormsg);

            return true;
        }//根据FPID(工号)添加人脸

        private void ProcessFaceDataRecordCallback(uint dwType, IntPtr lpBuffer, uint dwBufLen, IntPtr pUserData)
        {
            if (pUserData == null)
            {
                return;
            }
            if (dwType == (uint)CHCNetSDK.NET_SDK_CALLBACK_TYPE.NET_SDK_CALLBACK_TYPE_STATUS)
            {
                uint dwStatus = (uint)Marshal.ReadInt32(lpBuffer);
                if (dwStatus == (uint)CHCNetSDK.NET_SDK_CALLBACK_STATUS_NORMAL.NET_SDK_CALLBACK_STATUS_FAILED)
                {
                    DefWndProc(1001, 1);
                    //CHCNetSDK.PostMessage(pUserData, 1001, 1, 0);
                    //可以结束了，异常结束
                }
                else if (dwStatus == (uint)CHCNetSDK.NET_SDK_CALLBACK_STATUS_NORMAL.NET_SDK_CALLBACK_STATUS_EXCEPTION)
                {
                    DefWndProc(1001, 2);
                    //CHCNetSDK.PostMessage(pUserData, 1001, 2, 0);
                    //可以结束了，异常结束
                }
                else if (dwStatus == (uint)CHCNetSDK.NET_SDK_CALLBACK_STATUS_NORMAL.NET_SDK_CALLBACK_STATUS_PROCESSING)
                {
                    ;
                }
                else
                {
                    DefWndProc(1001, 3);
                    //CHCNetSDK.PostMessage(pUserData, 1001, 3, 0);
                    //可以结束了，异常结束
                }
            }
            else if (dwType == (uint)CHCNetSDK.NET_SDK_CALLBACK_TYPE.NET_SDK_CALLBACK_TYPE_DATA)
            {
                string strResponseStatus = Marshal.PtrToStringAnsi(lpBuffer);
                CResponseStatus JsonResponseStatus = new CResponseStatus();
                JsonResponseStatus = JsonConvert.DeserializeObject<CResponseStatus>(strResponseStatus);
                m_strFPID = JsonResponseStatus.FPID;

                DefWndProc(1003, JsonResponseStatus.statusCode);
                //CHCNetSDK.PostMessage(pUserData, 1003, JsonResponseStatus.statusCode, 0);

                if ((m_iFaceDataRecordIndex >= m_iFaceDataRecordCount) || (JsonResponseStatus.statusCode != 1))
                {
                    DefWndProc(1001, 4);
                    //CHCNetSDK.PostMessage(pUserData, 1001, 4, 0);
                    //可以结束了，正常（异常）结束
                    return;
                }
                DefWndProc(1002, 0);
                //CHCNetSDK.PostMessage(pUserData, 1002, 0, 0);
                //在主线程中发送下一个用户
            }
            return;
        }

        private bool SendFaceRecord(LssueinfoTODev Lssueinfo, string webRootPath, out string errormsg)
        {
            if (-1 == m_lFaceDataRecordHandle)
            {
                errormsg = "设备不在线";
                return false;
            }

            CFaceRecordData JsonFaceRecordData = new CFaceRecordData();

            JsonFaceRecordData.faceLibType = "blackFD";
            JsonFaceRecordData.FDID = "1";
            JsonFaceRecordData.FPID = Lssueinfo.UserID;

            string strFaceRecordData = JsonConvert.SerializeObject(JsonFaceRecordData);

            IntPtr ptrFaceRecordData = Marshal.StringToHGlobalAnsi(strFaceRecordData);

            CHCNetSDK.NET_DVR_JSON_DATA_CFG struJsonDataCfg = new CHCNetSDK.NET_DVR_JSON_DATA_CFG();
            struJsonDataCfg.dwSize = (uint)Marshal.SizeOf(struJsonDataCfg);
            struJsonDataCfg.lpJsonData = ptrFaceRecordData;
            struJsonDataCfg.dwJsonDataSize = (uint)strFaceRecordData.Length;

            string picpath;
            //if (Lssueinfo.picpath == "")
            //{
            //    picpath = webRootPath + "/" + Lssueinfo.UserID + ".jpg";
            //}
            //else
            //{
            picpath = webRootPath + "\\wwwroot" + Lssueinfo.picpath;
            //}
            FileStream fs = new FileStream(picpath, FileMode.OpenOrCreate);
            if (0 == fs.Length)
            {
                // MessageBox.Show("The picture is 0k,please input another picture!");
                Marshal.FreeHGlobal(ptrFaceRecordData);
                fs.Close();
                errormsg = "照片大小为0";
                return false;
            }
            if (200 * 1024 < fs.Length)
            {
                // MessageBox.Show("The picture is larger than 200k,please input another picture!");
                Marshal.FreeHGlobal(ptrFaceRecordData);
                fs.Close();
                errormsg = "照片大小大于200K";
                return false;
            }

            struJsonDataCfg.dwPicDataSize = (uint)fs.Length;
            int iLen = (int)struJsonDataCfg.dwPicDataSize;
            byte[] by = new byte[iLen];
            struJsonDataCfg.lpPicData = Marshal.AllocHGlobal(iLen);
            fs.Read(by, 0, iLen);
            Marshal.Copy(by, 0, struJsonDataCfg.lpPicData, iLen);
            fs.Close();

            IntPtr ptrJsonDataCfg = Marshal.AllocHGlobal(Marshal.SizeOf(struJsonDataCfg));
            Marshal.StructureToPtr(struJsonDataCfg, ptrJsonDataCfg, false);

            if (!CHCNetSDK.NET_DVR_SendRemoteConfig(m_lFaceDataRecordHandle, (int)CHCNetSDK.LONG_CFG_SEND_DATA_TYPE_ENUM.ENUM_SEND_JSON_DATA, ptrJsonDataCfg, (uint)Marshal.SizeOf(struJsonDataCfg)))
            {
                Marshal.FreeHGlobal(ptrFaceRecordData);
                Marshal.FreeHGlobal(struJsonDataCfg.lpPicData);
                Marshal.FreeHGlobal(ptrJsonDataCfg);
                errormsg = "人脸设置失败";
                return false;
            }
            Marshal.FreeHGlobal(ptrFaceRecordData);
            Marshal.FreeHGlobal(struJsonDataCfg.lpPicData);
            Marshal.FreeHGlobal(ptrJsonDataCfg);
            m_iFaceDataRecordIndex++;
            errormsg = string.Empty;
            return true;
        }

        public class CFaceRecordData
        {
            public string faceLibType { get; set; }
            public string FDID { get; set; }
            public string FPID { get; set; }
        }
        #endregion

        #region 梯控设备删除凭证

        public ResponseMessage DeleteByEmployeeNo(LssueVoucher Lssueinfo)
        {
            ResponseMessage message = new ResponseMessage();
            //删除单个工号,传入设备ID和工号ID、Dev_state,并根据dev_state判断设备是否在线，在线则调用该接口

            GetUserIDMod BuildP = new GetUserIDMod();
            List<GetUserIDMod> list = new List<GetUserIDMod>();

            bool result = DeleteUserInfo(Lssueinfo);
            //设备端已删除成功
            if (result == true)
            {
                //删除数据库中凭证绑定记录
                VoucherDAL da = new VoucherDAL();
                da.DeleteVoucherByOwner(Lssueinfo.DevID, Lssueinfo.ownerid);
            }
            else
            {
                message.errcode = 1;
                message.errmsg = "凭证删除失败";

            }
            return message;

        }//删除单个工号信息

        private bool DeleteUserInfo(LssueVoucher Lssueinfo)
        {
            IntPtr ptrOutBuf = Marshal.AllocHGlobal(1024);
            IntPtr ptrStatusBuffer = Marshal.AllocHGlobal(1024);

            for (int i = 0; i < 1024; i++)
            {
                Marshal.WriteByte(ptrOutBuf, i, 0);
                Marshal.WriteByte(ptrStatusBuffer, i, 0);
            }

            CHCNetSDK.NET_DVR_XML_CONFIG_INPUT struInput = new CHCNetSDK.NET_DVR_XML_CONFIG_INPUT();
            CHCNetSDK.NET_DVR_XML_CONFIG_OUTPUT struOuput = new CHCNetSDK.NET_DVR_XML_CONFIG_OUTPUT();

            string sUrl = "PUT /ISAPI/AccessControl/UserInfo/Delete?format=json";
            IntPtr ptrURL = Marshal.StringToHGlobalAnsi(sUrl);
            struInput.dwSize = (uint)Marshal.SizeOf(struInput);
            struInput.lpRequestUrl = ptrURL;
            struInput.dwRequestUrlLen = (uint)sUrl.Length;
            //delete timeout set 60s
            struInput.dwRecvTimeOut = 60000;

            CUserInfoDelCond JsonUserInfoDelCond = new CUserInfoDelCond();
            JsonUserInfoDelCond.UserInfoDelCond = new CUserInfoDelCondContent();
            JsonUserInfoDelCond.UserInfoDelCond.EmployeeNoList = new List<CEmployeeNoList>();

            //if (!m_bDeleteAll)
            //{
            //    foreach (ListViewItem item in this.listViewEmployeeNo.Items)
            //    {
            //        if (item.SubItems[1].Text != "")
            //        {
            CEmployeeNoList singleEmployeeNoList = new CEmployeeNoList();
            singleEmployeeNoList.employeeNo = Lssueinfo.UserID;//"3884";
            JsonUserInfoDelCond.UserInfoDelCond.EmployeeNoList.Add(singleEmployeeNoList);
            //        }
            //    }
            //}

            string strUserInfoDelCond = JsonConvert.SerializeObject(JsonUserInfoDelCond);

            IntPtr ptrInBuffer = Marshal.StringToHGlobalAnsi(strUserInfoDelCond);

            struInput.lpInBuffer = ptrInBuffer;
            struInput.dwInBufferSize = (uint)strUserInfoDelCond.Length;

            struOuput.dwSize = (uint)Marshal.SizeOf(struOuput);
            struOuput.lpOutBuffer = ptrOutBuf;
            struOuput.dwOutBufferSize = 1024;
            struOuput.lpStatusBuffer = ptrStatusBuffer;
            struOuput.dwStatusSize = 1024;

            IntPtr ptrInput = Marshal.AllocHGlobal(Marshal.SizeOf(struInput));
            Marshal.StructureToPtr(struInput, ptrInput, false);
            IntPtr ptrOuput = Marshal.AllocHGlobal(Marshal.SizeOf(struOuput));
            Marshal.StructureToPtr(struOuput, ptrOuput, false);
            if (!CHCNetSDK.NET_DVR_STDXMLConfig(Lssueinfo.m_lUserID, ptrInput, ptrOuput))
            {//设备不在线删除失败
                //ListViewItem listItem = new ListViewItem();
                //listItem.Text = "Fail";
                //string strTemp = string.Format("Delete User Info Fail,Error Code={0}", CHCNetSDK.NET_DVR_GetLastError());
                //listItem.SubItems.Add(strTemp);
                //this.AddList(listViewMessage, listItem);
                return false;
            }
            else
            {
                //ListViewItem listItem = new ListViewItem();
                //listItem.Text = "Succ";
                //string strTemp = string.Format("Delete User Info Success");
                //listItem.SubItems.Add(strTemp);
                //this.AddList(listViewMessage, listItem);

                string strResponseStatus = Marshal.PtrToStringAnsi(struOuput.lpOutBuffer);
                CResponseStatus JsonResponseStatus = new CResponseStatus();
                JsonResponseStatus = JsonConvert.DeserializeObject<CResponseStatus>(strResponseStatus);
            }

            Marshal.FreeHGlobal(ptrOutBuf);
            Marshal.FreeHGlobal(ptrStatusBuffer);
            Marshal.FreeHGlobal(ptrInBuffer);
            Marshal.FreeHGlobal(ptrInput);
            Marshal.FreeHGlobal(ptrOuput);
            Marshal.FreeHGlobal(ptrURL);
            return true;
        }//删除单个工号过程

        public class CUserInfoDelCond
        {
            public CUserInfoDelCondContent UserInfoDelCond { get; set; }
        }

        public class CUserInfoDelCondContent
        {
            public List<CEmployeeNoList> EmployeeNoList { get; set; }
        }

        #endregion

        public void CheckStatus(List<DeviceInfo> list)
        {
            Dictionary<string, Socket> dic = fxserver.devid_dict;
            RecordDAL da = new RecordDAL();
            foreach (var item in list)
            {
                if (dic.ContainsKey(item.DeviceNO) && item.DeviceState == "离线")
                {
                    da.InsertDeviceRecord(item.DeviceUuid, item.DeviceNO, item.DeviceIP, "在线");
                }
                else if (!dic.ContainsKey(item.DeviceNO) && item.DeviceState == "在线")
                {
                    da.InsertDeviceRecord(item.DeviceUuid, item.DeviceNO, item.DeviceIP, "离线");
                }
            }
        }

        public JLLssueinfo JLVoucherIssue(string wwwroot, VoucherInfo voucher)
        {
            DeviceDAL deviceDAL = new DeviceDAL();
            DeviceInfo deviceInfo = deviceDAL.LoadDeviceByIp(voucher.DeviceIP);
            JLLssueinfo jLLssueinfo = new JLLssueinfo();
            jLLssueinfo.Name = "personListRequest";
            jLLssueinfo.UUID = deviceInfo.DeviceUuid;
            jLLssueinfo.Session = deviceInfo.Session;
            jLLssueinfo.TimeStamp = GetTimeStamp();
            JLLssueinfoData jLLssueinfoData = new JLLssueinfoData();
            jLLssueinfoData.Action = "addPerson";
            if (string.IsNullOrEmpty(voucher.PicturePath))
            {
                jLLssueinfoData.AddType = 3;
            }
            else
            {
                jLLssueinfoData.AddType = 0;
            }
            jLLssueinfoData.PersonType = 2;
            JLLssueinfoPerson jLLssueinfoPerson = new JLLssueinfoPerson();
            jLLssueinfoPerson.PersonId = voucher.UUID;
            jLLssueinfoPerson.PersonName = voucher.OwnerName;
            jLLssueinfoPerson.PersonCover = 1;
            jLLssueinfoPerson.Sex = 1;
            jLLssueinfoPerson.LimitTime = 1;
            jLLssueinfoPerson.StartTime = Convert.ToDateTime(voucher.EffectiveStarttime).ToString("yyyy-MM-dd HH:mm:ss");
            jLLssueinfoPerson.EndTime = Convert.ToDateTime(voucher.EffectiveEndtime).ToString("yyyy-MM-dd HH:mm:ss");
            jLLssueinfoPerson.PersonIdentity = voucher.OwnerType;
            jLLssueinfoPerson.ICCardNo = voucher.CardNO;
            JLPersonExtension jLPersonExtension = new JLPersonExtension();
            jLPersonExtension.AuthData = voucher.AuthData;
            jLLssueinfoPerson.PersonExtension = jLPersonExtension;
            string url = wwwroot + "/wwwroot" + voucher.PicturePath;
            jLLssueinfoPerson.PersonPhoto = ImgToBase64String(url);
            //jLLssueinfoPerson.PersonPhoto = voucher.PhotoData;
            jLLssueinfoPerson.FeatureValue = "";

            jLLssueinfoData.PersonInfo = jLLssueinfoPerson;
            jLLssueinfo.Data = jLLssueinfoData;
            LogHelper.Log(JsonConvert.SerializeObject(jLLssueinfo));
            return jLLssueinfo;
        }

        public int GetTimeStamp()
        {
            TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt32(ts.TotalSeconds);
        }

        private string ImgToBase64String(string Imagefilename)
        {
            try
            {
                Bitmap bmp = new Bitmap(Imagefilename);

                MemoryStream ms = new MemoryStream();
                bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                byte[] arr = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(arr, 0, (int)ms.Length);
                ms.Close();
                return Convert.ToBase64String(arr);
            }
            catch (Exception ex)
            {
                LogHelper.Log(ex.ToString());
                return "";
            }
        }

        public JLLssueinfoDelAll JLVoucherDelAll(DeviceInfo deviceInfo, int PersonIdentity)
        {
            JLLssueinfoDelAll jLLssueinfo = new JLLssueinfoDelAll();
            jLLssueinfo.Name = "personListRequest";
            jLLssueinfo.UUID = deviceInfo.DeviceUuid;
            jLLssueinfo.Session = deviceInfo.Session;
            jLLssueinfo.TimeStamp = GetTimeStamp();
            JLLssueinfoDelAllData jLLssueinfoData = new JLLssueinfoDelAllData();
            jLLssueinfoData.Action = "deletePersonList";
            jLLssueinfoData.PersonType = 0;
            jLLssueinfoData.PersonIdentity = PersonIdentity;
            jLLssueinfo.Data = jLLssueinfoData;
            return jLLssueinfo;
        }

        public JLLssueinfoDelBatch JLVoucherDelBatch(List<JLLssueinfoDelBatchPerson> personlist, DeviceInfo deviceInfo)
        {
            JLLssueinfoDelBatch jLLssueinfo = new JLLssueinfoDelBatch();
            jLLssueinfo.Name = "personListRequest";
            jLLssueinfo.UUID = deviceInfo.DeviceUuid;
            jLLssueinfo.Session = deviceInfo.Session;
            jLLssueinfo.TimeStamp = GetTimeStamp();
            JLLssueinfoDelBatchData jLLssueinfoData = new JLLssueinfoDelBatchData();
            jLLssueinfoData.Action = "deletePersons";
            jLLssueinfoData.PersonType = 0;
            jLLssueinfoData.PersonList = personlist;
            jLLssueinfo.Data = jLLssueinfoData;
            return jLLssueinfo;
        }

        public ResponseMessage ClearVoucher(int deviceid, int personIdentity)
        {
            ResponseMessage message = new ResponseMessage();

            VoucherDAL da = new VoucherDAL();
            bool result = da.ClearVoucherByDevice(deviceid, personIdentity);
            if (result)
            {
                message.errcode = 0;
            }
            else
            {
                message.errcode = 1;
                message.errmsg = "清空凭证失败";
            }

            return message;
        }

        public ResponseMessage DeleteBatchVoucher(List<JLLssueinfoDelBatchPerson> list, int deviceid)
        {
            ResponseMessage message = new ResponseMessage();
            VoucherDAL da = new VoucherDAL();

            foreach (var item in list)
            {
                da.ClearBatchVoucher(deviceid, item.PersonId);
            }

            return message;
        }

        public ResponseMessage UpdateLssuestate(int id, int state)
        {
            ResponseMessage message = new ResponseMessage();

            VoucherDAL da = new VoucherDAL();
            bool result = da.UpdateLssuestate(id, state);
            if (result)
            {
                message.errcode = 0;
            }
            else
            {
                message.errcode = 1;
                message.errmsg = "清空凭证失败";
            }

            return message;
        }

        public ResponseMessage UpdatePersonLssuestate(int id, int state)
        {
            ResponseMessage message = new ResponseMessage();

            VoucherDAL da = new VoucherDAL();
            bool result = da.UpdatePersonLssuestate(id, state);
            if (result)
            {
                message.errcode = 0;
            }
            else
            {
                message.errcode = 1;
                message.errmsg = "清空凭证失败";
            }

            return message;
        }

        public ResponseMessage JLVoucherClearAll(int deviceid, int personIdentity)
        {
            ResponseMessage message = new ResponseMessage();
            VoucherBUS BUS = new VoucherBUS();
            DeviceDAL da = new DeviceDAL();
            DeviceInfo deviceInfo = da.LoadDeviceInfo(deviceid);
            JLLssueinfoDelAll info = BUS.JLVoucherDelAll(deviceInfo, personIdentity);
            string ss = JsonConvert.SerializeObject(info);
            string re = HttpClientPost("http://" + deviceInfo.DeviceIP + ":8011/Request", info);
            JLLssueinfoReturn jLLssueinfoReturn = JsonConvert.DeserializeObject<JLLssueinfoReturn>(re);
            if (jLLssueinfoReturn.Name == "personListResponse" && jLLssueinfoReturn.Code == 1)
            {
                message = BUS.ClearVoucher(deviceid, personIdentity);
            }
            else
            {
                message.errcode = 1;
                message.errmsg = ErrorCode(jLLssueinfoReturn);
                message.data = null;
                message.total = 0;
            }

            return message;
        }

        public string HttpClientPost(string url, object datajson)
        {
            HttpClient httpClient = new HttpClient();//http对象
            //表头参数
            httpClient.DefaultRequestHeaders.Accept.Clear();
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            //转为链接需要的格式
            HttpContent httpContent = new JsonContent(datajson);
            //请求
            HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;
            if (response.IsSuccessStatusCode)
            {
                Task<string> t = response.Content.ReadAsStringAsync();
                if (t != null)
                {
                    return t.Result;
                }
            }
            return "";
        }

        public string N71SPHttpClientPost(string url, string datajson)
        {
            HttpClient httpClient = new HttpClient();//http对象
            //表头参数
            httpClient.DefaultRequestHeaders.Accept.Clear();
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            //转为链接需要的格式
            var content = new StringContent(datajson, Encoding.UTF8, "application/json");
            //请求
            HttpResponseMessage response = httpClient.PostAsync(url, content).Result;
            if (response.IsSuccessStatusCode)
            {
                Task<string> t = response.Content.ReadAsStringAsync();
                if (t != null)
                {
                    return t.Result;
                }
            }
            return "";
        }

        public string ErrorCode(JLLssueinfoReturn jLLssueinfoReturn)
        {
            string errormsg = "";
            switch (jLLssueinfoReturn.Code)
            {
                case 1001: errormsg = "设备未注册/注册失败"; break;
                case 1002: errormsg = "JSON 解析错误"; break;
                case 1003: errormsg = "Session无效"; break;
                case 1004: errormsg = "TimeStamp 无效"; break;
                case 1005: errormsg = "Sign无效"; break;
                case 1006: errormsg = "Name无效"; break;
                case 1101: errormsg = "Data无效"; break;
                case 1102: errormsg = "Action无效"; break;
                case 1103: errormsg = "PersonType无效"; break;
                case 1104: errormsg = "PersonId无效"; break;
                case 1105: errormsg = "GetPhoto错误"; break;
                case 1106: errormsg = "Action无效"; break;
                case 1107: errormsg = "PersonInfo/PersonInfoList无效"; break;
                case 1108: errormsg = "PersonName无效"; break;
                case 1109: errormsg = "PersonPhoto无效"; break;
                case 1110:
                    switch (jLLssueinfoReturn.Data.Result)
                    {
                        case 0: errormsg = jLLssueinfoReturn.Message; break;
                        case -1: errormsg = jLLssueinfoReturn.Message; break;
                        case -2: errormsg = "提取特征值失败"; break;
                        case -3: errormsg = "文件名字编号重复"; break;
                        case -4: errormsg = "库满"; break;
                        case -5: errormsg = "添加超时"; break;
                        case -6: errormsg = "参数错误"; break;
                        case -7: errormsg = "文件太大"; break;
                        case -8: errormsg = "存储空间不足"; break;
                        case -9: errormsg = "文件打开失败"; break;
                        case -10: errormsg = "没有数据库"; break;
                        case -11: errormsg = "图片读取失败"; break;
                        case -12: errormsg = "数据库文件损坏"; break;
                        case -13: errormsg = "图片质量差"; break;
                        case -14: errormsg = "图片尺寸错误，宽高不能为奇数"; break;
                        case -15: errormsg = "检测人脸失败"; break;
                        case -16: errormsg = "图片格式错误"; break;
                        case -17: errormsg = "人脸区域错误"; break;
                        case -18: errormsg = "算法创建句柄错误"; break;
                        case -19: errormsg = "设备忙"; break;
                        case -20: errormsg = "文件写入失败"; break;
                        case -21: errormsg = "删除失败(未找到对应的ID删除)"; break;
                        case -22: errormsg = "分配内存失败"; break;
                        case -23: errormsg = "名单数人数为空"; break;
                        case -24: errormsg = "临时名单有效时间错误"; break;
                        case -51: errormsg = "数据异常"; break;
                        case -52: errormsg = "数据标志错误"; break;
                        case -53: errormsg = "数据长度错误"; break;
                        case -54: errormsg = "特征值数据长度错误"; break;
                        case -55: errormsg = "芯片厂商错误"; break;
                        case -56: errormsg = "芯片类型错误"; break;
                        case -57: errormsg = "算法厂商错误"; break;
                        case -58: errormsg = "算法类型错误"; break;
                        case -59: errormsg = "设备类型错误"; break;
                        case -60: errormsg = "算法版本错误"; break;
                        case -61: errormsg = "数据库操作失败"; break;
                        case -62: errormsg = "查无此人"; break;
                        case -5102: errormsg = "Plan字段不正确"; break;
                        case -5103: errormsg = "Date字段不正确"; break;
                        case -5104: errormsg = "重复签到"; break;
                        case -5105: errormsg = "无数据（未发生预案）"; break;
                        case -5106: errormsg = "阈值超出范围"; break;
                        case -5107: errormsg = "缓冲超出范围"; break;
                    };
                    break;
                case 1111: errormsg = jLLssueinfoReturn.Message; break;
                case 1112: errormsg = "设备不在线"; break;
                case 1113: errormsg = "设备处理超时"; break;
                case 1114: errormsg = "内存分配失败"; break;
                case 1115: errormsg = "请求地址无效"; break;
                case 1116: errormsg = "下载文件失败"; break;
                default: errormsg = "异常" + jLLssueinfoReturn.Message; break;
            }
            return errormsg;
        }

        public ResponseMessage AddProVoucher(OwnerDeviceVoucher ownerDevice)
        {
            ResponseMessage message = new ResponseMessage();
            VoucherDAL dAL = new VoucherDAL();
            VoucherInfo voucher1 = new VoucherInfo();
            voucher1.OwnerID = ownerDevice.OwnerInfo.ID;
            List<VoucherInfo> list = dAL.QueryExistVoucher(voucher1);
            foreach (var item in ownerDevice.DeviceVoucher_List)
            {
                ModbusRtu modbus = new ModbusRtu();
                VoucherDAL voucherDAL = new VoucherDAL();
                VoucherInfo voucher = new VoucherInfo();
                voucher.OwnerID = ownerDevice.OwnerInfo.ID;
                voucher.AuthorizedFloor = item.FloorInfo;
                if (ownerDevice.OwnerInfo.VirtualCard == 2)//梯控卡-开
                {
                    voucher.AuthData = modbus.GetLiftStateCmd(1);
                    voucher.EffectiveEndtime = Convert.ToDateTime("2038-01-01").ToString("yyyy-MM-dd HH:mm:ss");
                }
                else if (ownerDevice.OwnerInfo.VirtualCard == 3)//梯控卡-关
                {
                    voucher.AuthData = modbus.GetLiftStateCmd(0);
                    voucher.EffectiveEndtime = Convert.ToDateTime("2038-01-01").ToString("yyyy-MM-dd HH:mm:ss");
                }
                else
                {
                    voucher.AuthData = modbus.GetCallAdminCmd(ownerDevice.OwnerInfo.UUID);
                    voucher.EffectiveEndtime = Convert.ToDateTime(ownerDevice.OwnerInfo.MaxTime).ToString("yyyy-MM-dd HH:mm:ss");
                }
                voucher.projectID = ownerDevice.OwnerInfo.projectID;
                voucher.DeviceID = item.DeviceID;
                voucher.EffectiveStarttime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                if (list.Exists(t => t.DeviceID == item.DeviceID))
                {
                    voucherDAL.UpdateVoucherByDev(voucher);
                }
                else
                {
                    voucherDAL.AddVoucher(voucher);
                }
            }
            return message;
        }

        public ResponseMessage JLVoucherIssue(int id, string deviceip, string path)
        {
            ResponseMessage message = new ResponseMessage();
            VoucherBUS BUS = new VoucherBUS();
            VoucherDAL da = new VoucherDAL();
            VoucherInfo voucher = da.LoadVoucher(id);
            if (voucher.VirtualCard == 1 && string.IsNullOrEmpty(voucher.PicturePath))
            {
                message.errcode = 1;
                message.errmsg = "人脸和卡信息都为空，下发失败";
            }
            else
            {
                JLLssueinfo info = BUS.JLVoucherIssue(path, voucher);
                string re = HttpClientPost("http://" + deviceip + ":8011/Request", info);
                JLLssueinfoReturn jLLssueinfoReturn = JsonConvert.DeserializeObject<JLLssueinfoReturn>(re);
                if (jLLssueinfoReturn.Name == "personListResponse" && jLLssueinfoReturn.Code == 1)
                {
                    message = BUS.UpdateLssuestate(id, 1);
                }
                else
                {
                    message.errcode = 1;
                    message.errmsg = ErrorCode(jLLssueinfoReturn);
                    message.data = null;
                    message.total = 0;
                }
            }
            return message;
        }

        public ResponseMessage OneClickVoucherIssue(ProVoucherInfo proVoucher, string path)
        {
            ResponseMessage message = new ResponseMessage();
            string failinfo = string.Empty;
            foreach (var item in proVoucher.Vouchers_List)
            {
                try
                {
                    if (item.DeviceState == "在线")
                    {
                        if (item.VirtualCard == 1 && string.IsNullOrEmpty(item.PicturePath))
                        {
                            failinfo += item.DeviceName + ",";
                        }
                        else
                        {
                            JLLssueinfo info = JLVoucherOneClick(path, item);
                            string re = HttpClientPost("http://" + item.DeviceIP + ":8011/Request", info);
                            JLLssueinfoReturn jLLssueinfoReturn = JsonConvert.DeserializeObject<JLLssueinfoReturn>(re);
                            if (jLLssueinfoReturn.Name == "personListResponse" && jLLssueinfoReturn.Code == 1)
                            {
                                message = UpdateLssuestate(item.ID, 1);
                                if (message.errcode == 1)
                                {
                                    failinfo += item.DeviceName + ",";
                                }
                            }
                            else
                            {
                                failinfo += item.DeviceName + ",";
                            }
                        }
                    }
                    else
                    {
                        failinfo += item.DeviceName + ",";
                    }
                }
                catch
                {
                    continue;
                }
            }
            if (failinfo.Length > 0)
            {
                message.errcode = 1;
                message.errmsg = "设备" + failinfo.Substring(0, failinfo.Length - 1) + "下发失败";
            }
            else
            {
                message.errcode = 0;
            }
            return message;
        }

        public JLLssueinfo JLVoucherOneClick(string wwwroot, VoucherInfo voucher)
        {
            DeviceDAL deviceDAL = new DeviceDAL();
            DeviceInfo deviceInfo = deviceDAL.LoadDeviceByIp(voucher.DeviceIP);
            JLLssueinfo jLLssueinfo = new JLLssueinfo();
            jLLssueinfo.Name = "personListRequest";
            jLLssueinfo.UUID = deviceInfo.DeviceUuid;
            jLLssueinfo.Session = deviceInfo.Session;
            jLLssueinfo.TimeStamp = GetTimeStamp();
            JLLssueinfoData jLLssueinfoData = new JLLssueinfoData();
            jLLssueinfoData.Action = "addPerson";
            if (voucher.VirtualCard == 0 && string.IsNullOrEmpty(voucher.PicturePath))
            {
                jLLssueinfoData.AddType = 3;
            }
            else
            {
                jLLssueinfoData.AddType = 0;
            }
            jLLssueinfoData.PersonType = 2;
            JLLssueinfoPerson jLLssueinfoPerson = new JLLssueinfoPerson();
            jLLssueinfoPerson.PersonId = voucher.UUID;
            jLLssueinfoPerson.PersonName = voucher.OwnerName;
            jLLssueinfoPerson.PersonCover = 1;
            jLLssueinfoPerson.Sex = 1;
            jLLssueinfoPerson.LimitTime = 1;
            jLLssueinfoPerson.StartTime = Convert.ToDateTime(voucher.EffectiveStarttime).ToString("yyyy-MM-dd HH:mm:ss");
            jLLssueinfoPerson.EndTime = Convert.ToDateTime(voucher.EffectiveEndtime).ToString("yyyy-MM-dd HH:mm:ss");
            jLLssueinfoPerson.PersonIdentity = voucher.OwnerType;
            jLLssueinfoPerson.ICCardNo = voucher.CardNO;
            JLPersonExtension jLPersonExtension = new JLPersonExtension();
            jLPersonExtension.AuthData = voucher.AuthData;
            jLLssueinfoPerson.PersonExtension = jLPersonExtension;
            string url = wwwroot + "/wwwroot" + voucher.PicturePath;
            jLLssueinfoPerson.PersonPhoto = ImgToBase64String(url);
            //jLLssueinfoPerson.PersonPhoto = voucher.PhotoData;
            jLLssueinfoPerson.FeatureValue = "";
            //jLLssueinfoPerson.AuthData = voucher.AuthData;
            jLLssueinfoData.PersonInfo = jLLssueinfoPerson;
            jLLssueinfo.Data = jLLssueinfoData;
            return jLLssueinfo;
        }

        public ResponseMessage OneClickVoucherDel(ProVoucherInfo proVoucher)
        {
            ResponseMessage message = new ResponseMessage();
            string failinfo = string.Empty;
            foreach (var item in proVoucher.Vouchers_List)
            {
                try
                {
                    if (item.DeviceState == "在线")
                    {
                        if (item.Flag == 1)
                        {
                            //JLLssueinfoDel info = JLVoucherDelSingle(item.ID);
                            JLLssueinfoDel info = JLVoucherDel(item);
                            string re = HttpClientPost("http://" + item.DeviceIP + ":8011/Request", info);
                            JLLssueinfoReturn jLLssueinfoReturn = JsonConvert.DeserializeObject<JLLssueinfoReturn>(re);
                            if (jLLssueinfoReturn.Name == "personListResponse" && jLLssueinfoReturn.Code == 1)
                            {
                                message = DelVoucher(item);
                                if (message.errcode == 1)
                                {
                                    failinfo += item.DeviceName + ",";
                                }
                            }
                            else if (jLLssueinfoReturn.Name == "personListResponse" && jLLssueinfoReturn.Data.Result == -21 && jLLssueinfoReturn.Code == 1110)
                            {
                                message = DelVoucher(item);
                                if (message.errcode == 1)
                                {
                                    failinfo += item.DeviceName + ",";
                                }
                            }
                            else
                            {
                                failinfo += item.DeviceName + ",";
                            }
                        }
                        else
                        {
                            message = DelVoucher(item);
                            if (message.errcode == 1)
                            {
                                failinfo += item.DeviceName + ",";
                            }
                        }
                    }
                    else
                    {
                        failinfo += item.DeviceName + ",";
                    }
                }
                catch
                {
                    continue;
                }
            }
            if (failinfo.Length > 0)
            {
                message.errcode = 1;
                message.errmsg = "设备" + failinfo.Substring(0, failinfo.Length - 1) + "删除失败";
            }
            else
            {
                message.errcode = 0;
            }
            return message;
        }

        public JLLssueinfoDel JLVoucherDel(VoucherInfo voucher)
        {
            VoucherDAL da = new VoucherDAL();
            DeviceDAL deviceDAL = new DeviceDAL();
            DeviceInfo deviceInfo = deviceDAL.LoadDeviceByIp(voucher.DeviceIP);
            JLLssueinfoDel jLLssueinfo = new JLLssueinfoDel();
            jLLssueinfo.Name = "personListRequest";
            jLLssueinfo.UUID = deviceInfo.DeviceUuid;
            jLLssueinfo.Session = deviceInfo.Session;
            jLLssueinfo.TimeStamp = GetTimeStamp();
            JLLssueinfoDelData jLLssueinfoData = new JLLssueinfoDelData();
            jLLssueinfoData.Action = "deletePerson";
            jLLssueinfoData.PersonType = 2;
            jLLssueinfoData.PersonId = voucher.UUID;
            jLLssueinfo.Data = jLLssueinfoData;
            return jLLssueinfo;
        }

        public bool ImportVoucher(VoucherInfo voucher)
        {
            ModbusRtu modbus = new ModbusRtu();
            if (voucher.OwnerType == 2)
            {
                voucher.AuthData = modbus.GetCallAdminCmd(voucher.UUID);
            }
            else
            {
                string phyfloor = SortFloor(voucher.AuthorizedFloor, voucher.FloorInfo, voucher.pFloorInfo);
                voucher.AuthData = modbus.GetCallCmd(phyfloor, voucher.UUID);
            }
            VoucherDAL voucherDAL = new VoucherDAL();
            bool result = voucherDAL.AddVoucher(voucher);

            return result;
        }

        public ResponseMessage N71SPDeviceLogin(string ip, string username, string password, int forelogin)
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                DeviceLoginInfo deviceLoginInfo = new DeviceLoginInfo();
                DeviceLoginInfoData deviceLoginInfoData = new DeviceLoginInfoData();
                deviceLoginInfoData.UserName = username;
                deviceLoginInfoData.Password = password;
                deviceLoginInfoData.ForceLogin = forelogin;
                deviceLoginInfo.Params = deviceLoginInfoData;
                string data = JsonConvert.SerializeObject(deviceLoginInfo).Replace("Params", "params");
                string re = N71SPHttpClientPost("http://" + ip + "/api/system/login", data);
                LoginReturn loginReturn = JsonConvert.DeserializeObject<LoginReturn>(re);
                if (loginReturn.method == "login" && loginReturn.result == 0)
                {
                    DeviceDAL deviceDAL = new DeviceDAL();
                    bool result = deviceDAL.UpdateToken(loginReturn.Params.Token, ip);
                    if (!result)
                    {
                        message.errcode = 1;
                        message.errmsg = "注册失败";
                    }
                }
                else
                {
                    message.errcode = 1;
                    message.errmsg = N71SPErrorCode(loginReturn.result);
                    message.data = null;
                    message.total = 0;
                }
            }
            catch (Exception ex)
            {

            }
            return message;
        }

        public string N71SPErrorCode(int code)
        {
            string errormsg = "";
            switch (code)
            {
                case 100: errormsg = "参数错误"; break;
                case 101: errormsg = "系统资源不足"; break;
                case 103: errormsg = "设备不存在"; break;
                case 107: errormsg = "设备已存在"; break;
                case 104: errormsg = "文件不存在"; break;
                case 105: errormsg = "文件已存在"; break;
                case 106: errormsg = "文件操作失败"; break;
                case 108: errormsg = "用户不存在"; break;
                case 110: errormsg = "用户已满"; break;
                case 109: errormsg = "用户已存在"; break;
                case 111: errormsg = "用户权限不足"; break;
                case 112: errormsg = "密码错误"; break;
                case 120: errormsg = "禁止关机"; break;
                case 121: errormsg = "禁止重启"; break;
                case 122: errormsg = "升级固件失败"; break;
                case 150: errormsg = "获取能力失败"; break;
                case 151: errormsg = "获取时间失败"; break;
                case 152: errormsg = "设置时间失败"; break;
                case 153: errormsg = "获取用户列表失败"; break;
                case 154: errormsg = "创建用户失败"; break;
                case 155: errormsg = "删除用户失败"; break;
                case 156: errormsg = "修改用户失败"; break;
                case 157: errormsg = "保存用户信息失败"; break;
                case 158: errormsg = "获取系统版本失败"; break;
                case 200: errormsg = "恢复默认失败"; break;
                case 201: errormsg = "读取配置失败"; break;
                case 202: errormsg = "保存配置失败"; break;
                case 203: errormsg = "更新配置失败"; break;
                case 400: errormsg = "注册预览失败"; break;
                case 401: errormsg = "注销预览失败"; break;
                case 402: errormsg = "开始预览失败"; break;
                case 403: errormsg = "结束预览失败"; break;
                case 404: errormsg = "预览数据错误"; break;
                case 420: errormsg = "触发抓图失败"; break;
                case 421: errormsg = "抓图数据错误"; break;
                case 440: errormsg = "网络回放失败"; break;
                case 441: errormsg = "停止回放失败"; break;
                case 500: errormsg = "创建人员失败"; break;
                case 501: errormsg = "删除人员失败"; break;
                case 502: errormsg = "更新人员失败"; break;
                case 503: errormsg = "人员不存在"; break;
                case 504: errormsg = "人员已存在"; break;
                case 505: errormsg = "人员图片错误，请确认是否为JPEG格式，图片尺寸不"; break;
                case 506: errormsg = "未能找到人脸"; break;
                case 507: errormsg = "人脸已存在"; break;
                case 508: errormsg = "读取照片失败"; break;
                case 509: errormsg = "读取记录失败"; break;
                case 999: errormsg = "未知错误"; break;
            }
            return errormsg;
        }

        public ResponseMessage N71SPVoucherIssue(int id, string deviceip, string path)
        {
            ResponseMessage message = new ResponseMessage();
            VoucherBUS BUS = new VoucherBUS();
            VoucherDAL da = new VoucherDAL();
            VoucherInfo voucher = da.LoadVoucher(id);
            if (voucher.VirtualCard == 1 && string.IsNullOrEmpty(voucher.PicturePath))
            {
                message.errcode = 1;
                message.errmsg = "人脸和卡信息都为空，下发失败";
            }
            else
            {
                DeviceDAL deviceDAL = new DeviceDAL();
                DeviceInfo deviceInfo = deviceDAL.LoadDeviceByIp(voucher.DeviceIP);

                if (!string.IsNullOrEmpty(voucher.PicturePath))
                {
                    N71SPLssuePicinfo n71SPLssuePicinfo = N71SPVoucherPicIssue(deviceInfo, path, voucher);
                    string pic_data = JsonConvert.SerializeObject(n71SPLssuePicinfo).Replace("ParamsInfo", "params");
                    string pic_re = N71SPHttpClientPost("http://" + deviceip + "/api/person/savePersonPicture", pic_data);
                    PersonReturnData PicLssueinfoReturn = JsonConvert.DeserializeObject<PersonReturnData>(pic_re);
                    if (PicLssueinfoReturn.method == "savePersonPicture" && PicLssueinfoReturn.result == 0)
                    {
                        N71SPLssueinfo info = BUS.N71SPVoucherIssue(deviceInfo, voucher);
                        if (voucher.VirtualCard == 1)
                        {
                            info.ParamsInfo.ICCardID = "";
                        }
                        string data = JsonConvert.SerializeObject(info).Replace("ParamsInfo", "params");
                        if (voucher.PicuploadFlag==1)
                        {
                            string re = N71SPHttpClientPost("http://" + deviceip + "/api/person/insertPerson", data);
                            PersonReturnData jLLssueinfoReturn = JsonConvert.DeserializeObject<PersonReturnData>(re);
                            if (jLLssueinfoReturn.method == "insertPerson" && jLLssueinfoReturn.result == 0)
                            {
                                message = BUS.UpdatePersonLssuestate(id,1);
                                message = BUS.UpdateLssuestate(id, 1);
                            }
                            else
                            {
                                message.errcode = 1;
                                message.errmsg = N71SPErrorCode(jLLssueinfoReturn.result);
                                message.data = null;
                                message.total = 0;
                            }
                        }
                        else
                        {
                            string re = N71SPHttpClientPost("http://" + deviceip + "/api/person/updatePerson", data);
                            PersonReturnData jLLssueinfoReturn = JsonConvert.DeserializeObject<PersonReturnData>(re);
                            if (jLLssueinfoReturn.method == "updatePerson" && jLLssueinfoReturn.result == 0)
                            {
                                message = BUS.UpdateLssuestate(id, 1);
                            }
                            else
                            {
                                message.errcode = 1;
                                message.errmsg = N71SPErrorCode(jLLssueinfoReturn.result);
                                message.data = null;
                                message.total = 0;
                            }
                        }
                    }
                    else
                    {
                        message.errcode = 1;
                        message.errmsg = N71SPErrorCode(PicLssueinfoReturn.result);
                    }
                }
            }
            return message;
        }

        public N71SPLssueinfo N71SPVoucherIssue(DeviceInfo deviceInfo, VoucherInfo voucher)
        {
            N71SPLssueinfo n71SPLssueinfo = new N71SPLssueinfo();
            N71SPLssueinfoData n71SPLssueinfoData = new N71SPLssueinfoData();
            DateTime starttime = Convert.ToDateTime(voucher.EffectiveStarttime);
            DateTime endtime = Convert.ToDateTime(voucher.EffectiveEndtime);
            n71SPLssueinfoData.PersonID = voucher.UUID;
            n71SPLssueinfoData.PersonName = voucher.OwnerName;
            n71SPLssueinfoData.DepartID = 1;
            n71SPLssueinfoData.Gender = 0;
            n71SPLssueinfoData.Authority = 1;
            n71SPLssueinfoData.ICCardID = voucher.CardNO;
            n71SPLssueinfoData.EffectiveTime = ConvertDateTimeInt(starttime);
            n71SPLssueinfoData.ExpireTime = ConvertDateTimeInt(endtime);
            n71SPLssueinfo.ParamsInfo = n71SPLssueinfoData;
            n71SPLssueinfo.Token = deviceInfo.Token;
            return n71SPLssueinfo;
        }

        private long ConvertDateTimeInt(DateTime time)
        {
            return (time.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
        }

        public N71SPLssuePicinfo N71SPVoucherPicIssue(DeviceInfo deviceInfo, string wwwroot, VoucherInfo voucher)
        {
            N71SPLssuePicinfo n71SPLssuePicinfo = new N71SPLssuePicinfo();
            N71SPLssuePicinfoData n71SPLssuePicinfoData = new N71SPLssuePicinfoData();
            n71SPLssuePicinfoData.PersonID = voucher.UUID;
            string url = wwwroot + "/wwwroot" + voucher.PicturePath;
            n71SPLssuePicinfoData.Picture = ImgToBase64String(url);
            n71SPLssuePicinfo.ParamsInfo = n71SPLssuePicinfoData;
            n71SPLssuePicinfo.Token = deviceInfo.Token;
            return n71SPLssuePicinfo;
        }

        public ResponseMessage N71SPVoucherDel(VoucherInfo voucher)
        {
            ResponseMessage message = new ResponseMessage();
            DeviceDAL deviceDAL = new DeviceDAL();
            DeviceInfo deviceInfo = deviceDAL.LoadDeviceByIp(voucher.DeviceIP);
            PersonDel personDel = new PersonDel();
            PersonDelData personDelData = new PersonDelData();
            personDelData.PersonID = voucher.UUID;
            personDel.ParamsInfo = personDelData;
            personDel.Token = deviceInfo.Token;

            string data = JsonConvert.SerializeObject(personDel).Replace("ParamsInfo", "params");
            string re = N71SPHttpClientPost("http://" + voucher.DeviceIP + "/api/person/deletePerson", data);
            PersonReturnData PicLssueinfoReturn = JsonConvert.DeserializeObject<PersonReturnData>(re);
            if (PicLssueinfoReturn.method == "deletePerson" && PicLssueinfoReturn.result == 0)
            {
                VoucherDAL da = new VoucherDAL();
                bool result = da.DeleteVoucher(voucher);
                if (result)
                {
                    message.errcode = 0;
                }
                else
                {
                    message.errcode = 1;
                }

            }
            else
            {
                message.errcode = 1;
                message.errmsg = N71SPErrorCode(PicLssueinfoReturn.result);
            }

            return message;
        }
    }
}